如何使用Newtonsoft.Json反序列化JSON数组

Ste*_*ven 21 c# json deserialization

[
   {
      "receiver_tax_id":"1002",
      "total":"6949,15",
      "receiver_company_name":"Das Company",
      "receiver_email":"info@another.com",
      "status":0
   },
   {
      "receiver_tax_id":"1001",
      "total":"39222,49",
      "receiver_company_name":"SAD company",
      "receiver_email":"info@mail.com",
      "status":1
   }
]
Run Code Online (Sandbox Code Playgroud)

嗨,这是我的Json数据,但我不能反序列化它.我想只检查"状态"值.(第一个对象"status"0,第二个对象"status"1).

示例定义:

public class Example 
{
    [JsonProperty("receiver_tax_id")] 
    public string receiver_tax_id { get; set; }
    [JsonProperty("total")] 
    public string total { get; set; }
    [JsonProperty("receiver_company_name")] 
    public string receiver_company_name { get; set; }
    [JsonProperty("receiver_email")] 
    public string receiver_email { get; set; }
    [JsonProperty("status")] 
    public int status { get; set; } 
}
Run Code Online (Sandbox Code Playgroud)

反序列化代码:

var des = (Example)JsonConvert.DeserializeObject(responseString, typeof(Example)); 
Console.WriteLine(des.status[0].ToString());
Run Code Online (Sandbox Code Playgroud)

Max*_*ruk 32

试试这段代码:

public class Receiver 
{
   public string receiver_tax_id { get; set;}
   public string total { get; set;}
   public string receiver_company_name { get; set;}
   public int status { get; set;}
}
Run Code Online (Sandbox Code Playgroud)

反序列化如下所示:

var result = JsonConvert.DeserializeObject<List<Receiver>>(responseString);
var status = result[0].status;
Run Code Online (Sandbox Code Playgroud)

  • 如果使用`[JsonProperty(“ receiver_tax_id”)]`,则可以根据需要命名属性。`[JsonProperty(“ status”)] public int MyOwnStatus {get; 组; }` (2认同)

Dan*_*inu 5

If you only care about checking status you can use the dynamic type of .NET (https://msdn.microsoft.com/en-us/library/dd264741.aspx)

dynamic deserialized = JObject.Parse(responseString); 
int status1 = deserialized[0].status; 
int status2 = deserialized[1].status; 
//
// do whatever
Run Code Online (Sandbox Code Playgroud)

This way you don't even need the Example class.

  • 应该是 JArray.Parse (或者 JToken.Parse + 检查 deserialized.Type 如果我们不确定输入实际上是否有数组) (3认同)