将JSON文本加载到c#中的类对象中

Vis*_*eet 19 c# json

如何将以下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作为类.

  • 令人惊讶的是每个人都跳过了这个答案.Upvoted. (11认同)
  • 是的,我认为这真的是当时要求的.这在VS2012中是一种迂回的事情(见这里:/sf/ask/1296866161/ -on-paste)现在在VS2017中,非常简单. (3认同)
  • 非常有用,当使用JsonConvert进行转换时,您可能必须将委托创建为数组.在我的例子中,这是我为了将JSON字符串转换为类而必须做的事情.JsonConvert.DeserializeObject <PanelFootnotes []>(FootnoteJSON.Value) (2认同)
  • 这不适用于大小 &gt; 5 MB 的 JSON 文件 (2认同)

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)

假设您要将其转换为Customerclasse的实例.你的类应该看起来类似于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文件的名称;