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

How do I deserialize a JSON array using Newtonsoft.Json

[
   {
      "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" 值。 (第一个对象 "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; } 
}

反序列化代码:

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

试试这个代码:

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;

您正在尝试将数组反序列化为 Example 对象。尝试对列表执行此操作:

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

如果您只关心检查 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 class。

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

我会做两件事:

  1. 让您的 class 遵循 .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. 使用通用 JsonConvert.DeserializeObject<T> 重载而不是您当前使用的非通用版本反序列化 List<Example>

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