繁体   English   中英

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

[英]Convert JSON array to a c# object collection

我有一个如下所示的JSON,

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

我需要将其转换为ac#对象。 我的对象类型如下-

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属性都为null,这怎么了? 我没有任何错误。

您还可以建议一个将CouchBase查询结果转换为.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>());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM