将JSON文本加载到c#中的类对象中
如何将以下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"]]] ] }
首先创建一个类来表示您的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 }
使用Newtonsoft JSON序列 化程序将json字符串反 序列化为相应的类对象。
var jsonInput = "{ org:'myOrg',des:'hello'}"; MyFlightDto flight = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonInput);
或者使用JavaScriptSerializer
将其转换为类( 不建议使用,因为newtonsoft json序列化程序似乎表现更好 )。
string jsonInput="have your valid json input here"; // JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); Customer objCustomer = jsonSerializer.Deserialize(jsonInput)
假设您要将其转换为Customer
classe的实例。 您的类应该类似于JSON
结构(属性)
我建议你使用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(json);
与其他JSON序列化技术的性能比较
要从字符串创建json类,请复制该字符串。
在Visual Sudio中,单击编辑>粘贴特殊>粘贴Json作为类。
这将获取一个json字符串并将其转换为您指定的任何类
public static T ConvertJsonToClass(this string json) { System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); return serializer.Deserialize (json); }