将JSON文本加载到C#中的类对象中
问题描述:
如何将以下Json Response转换为C#对象?
How can I convert the following Json Response to a C# object?
{ "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"]]]
] }
答
首先创建一个代表您的json数据的类.
First create a class to represent your json data.
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
}
使用Newtonsoft JSON序列化器来反序列化json字符串对应的类对象.
var jsonInput = "{ org:'myOrg',des:'hello'}";
MyFlightDto flight = Newtonsoft.Json.JsonConvert.DeserializeObject<MyFlightDto>(jsonInput);
或使用JavaScriptSerializer
将其转换为类(不推荐使用,因为newtonsoft json序列化器的性能似乎更好).
Or Use JavaScriptSerializer
to convert it to a class(not recommended as the newtonsoft json serializer seems to perform better).
string jsonInput="have your valid json input here"; //
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
Customer objCustomer = jsonSerializer.Deserialize<Customer >(jsonInput)
假设您要将其转换为Customer
类的实例.您的课程应类似于JSON
结构(属性)
Assuming you want to convert it to a Customer
classe's instance. Your class should looks similar to the JSON
structure (Properties)