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

时间:2015-12-05 09:53:27

标签: 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
   }
]

嗨,这是我的Json数据,但我无法对其进行反序列化。 我只想查看" status"值。 (第一个对象"状态" 0,第二个对象"状态" 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; } 
}

反序列化代码:

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

4 个答案:

答案 0 :(得分:28)

试试这段代码:

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;}
}

反序列化如下所示:

var result = JsonConvert.DeserializeObject<List<Receiver>>(responseString);
var status = result[0].status;

答案 1 :(得分:3)

如果您只关心检查status,可以使用dynamic类型的.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

这样你甚至不需要Example类。

答案 2 :(得分:1)

从您的代码和JSON样例中看,问题是您实际上是在反序列化List<Example>而不是单个Example

我会做两件事:

  1. 让您的类遵循.NET命名约定,因为您已经使用正确的JsonProperty属性作为前缀:

    public class Example 
    {
        [JsonProperty("receiver_tax_id")] 
        public string ReceiverTaxId { get; set; }
    
        [JsonProperty("total")] 
        public string Total { get; set; }
    
        [JsonProperty("receiver_company_name")] 
        public string ReceiverCompanyName { get; set; }
    
        [JsonProperty("receiver_email")] 
        public string ReceiverEmail { get; set; }
    
        [JsonProperty("status")] 
        public int Status{ get; set; } 
    }
    
  2. 使用通用List<Example>重载而不是您当前使用的非通用版本反序列化JsonConvert.DeserializeObject<T>

    var des = JsonConvert.DeserializeObject<List<Example>>(responseString); 
    Console.WriteLine(des[0].Status);
    

答案 3 :(得分:0)

您正在尝试将数组反序列化为Example对象。请尝试将其添加到列表中:

var des = JsonConvert.DeserializeObject(responseString, typeof(List<Example>)) as List<Example>;