将JSON数组转换为c#对象集合



我有一个JSON像下面,

[
  {
    "document":
            {
                "createdDate":1476996267864,
                "processedDate":1476996267864,
                "taxYear":"2015",
                "type":"user_document"
            }
    },
  {
     "document":
            {
                "createdDate":1476998303463,
                "processedDate":0,
                "taxYear":"2015",
                "type":"user_document"
            }
    }
  ]

我需要把它转换成c#对象。我的对象类型如下-

public class UserDocument
    {
        [JsonProperty(PropertyName = "type")]
        public string type { get; set; }
        [JsonProperty(PropertyName = "taxYear")]
        public string taxYear { get; set; }
        [JsonProperty(PropertyName = "createdDate")]
        public string createdDate { get; set; }
        [JsonProperty(PropertyName = "processedDate")]
        public string processedDate { get; set; }
    }

我使用下面的代码来反序列化json但所有UserDocument属性都是null

 var test = JsonConvert.DeserializeObject<List<UserDocument>>(jsonString);

为什么我得到所有UserDocument属性为空,这里有什么问题?我没有得到任何错误。

你也可以建议一个很好的例子,在得到CouchBase queryresult到一个。net对象。

似乎您的json格式不正确。如果我说json是

[
    "document":
            {
                "createdDate":1476996267864,
                "processedDate":1476996267864,
                "taxYear":"2015",
                "type":"user_document"
            },
     "document":
            {
                "createdDate":1476998303463,
                "processedDate":0,
                "taxYear":"2015",
                "type":"user_document"
            }
  ]

然后创建一个像

这样的模型
public class Document
{
   public UserDocument document {get;set;}
}

并将UserDocument模型的createdDateprocessedDate属性更改为double,因为它就像json

中的那样
public class UserDocument
    {
        [JsonProperty(PropertyName = "type")]
        public string type { get; set; }
        [JsonProperty(PropertyName = "taxYear")]
        public string taxYear { get; set; }
        [JsonProperty(PropertyName = "createdDate")]
        public double createdDate { get; set; }
        [JsonProperty(PropertyName = "processedDate")]
        public double processedDate { get; set; }
    }

,然后反序列化

var test = JsonConvert.DeserializeObject<List<Document>>(jsonString);

像这样(使用Newtonsoft.Json.Linq):

var documents = JArray.Parse(json).Select(t => t["document"].ToObject<UserDocument>());

相关内容

  • 没有找到相关文章