如何将以下Json响应转换为C#对象?
{ "err_code": "0", "org": "CGK", "des": "SIN", "flight_date": "20120719",
"schedule":
[
["W2-888","20120719","20120719","1200","1600","03h00m","737-200","0",[["K","9"],["F","9"],["L","9"],["M","9"],["N","9"],["P","9"],["C","9"],["O","9"]]],
["W2-999","20120719","20120719","1800","2000","01h00m","MD-83","0",[["K","9"],["L","9"],["M","9"],["N","9"]]]
] }
Run Code Online (Sandbox Code Playgroud)
Ole*_*our 51
要从字符串创建json类,请复制该字符串.
在Visual Sudio中,单击编辑>粘贴特殊>粘贴Json作为类.
Shy*_*yju 44
首先创建一个表示json数据的类.
public class MyFlightDto
{
public string err_code { get; set; }
public string org { get; set; }
public string flight_date { get; set; }
// Fill the missing properties for your data
}
Run Code Online (Sandbox Code Playgroud)
使用Newtonsoft JSON序列化到反序列化JSON字符串到它的相应的类对象.
var jsonInput = "{ org:'myOrg',des:'hello'}";
MyFlightDto flight = Newtonsoft.Json.JsonConvert.DeserializeObject<MyFlightDto>(jsonInput);
Run Code Online (Sandbox Code Playgroud)
或者使用 JavaScriptSerializer
将其转换为类(不建议使用,因为newtonsoft json序列化程序似乎表现更好).
string jsonInput="have your valid json input here"; //
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
Customer objCustomer = jsonSerializer.Deserialize<Customer >(jsonInput)
Run Code Online (Sandbox Code Playgroud)
假设您要将其转换为Customer
classe的实例.你的类应该看起来类似于JSON
结构(属性)
Tal*_*lha 40
我建议你使用JSON.NET
.它是一个开源库,用于将c#对象序列化和反序列化为json和Json对象到.net对象中...
序列化示例:
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string json = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "Expiry": new Date(1230422400000),
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
Run Code Online (Sandbox Code Playgroud)
与其他JSON序列化技术的性能比较
小智 5
复制您的 Json 并粘贴到http://json2csharp.com/上的文本框中,然后单击“生成”按钮,
将使用该 cs 文件生成一个 cs 类,如下所示:
var generatedcsResponce = JsonConvert.DeserializeObject<RootObject>(yourJson);
Run Code Online (Sandbox Code Playgroud)
其中RootObject
是生成的cs文件的名称;
归档时间: |
|
查看次数: |
104664 次 |
最近记录: |