blue
blue

Reputation: 863

Convert JSON array to a c# object collection

I've a JSON like below,

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

I need to convert it into a c# object. My object type is as below-

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

    }

I'm using below code to deserialize the json but all UserDocument properties are null

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

Why am I getting all UserDocument properties are null, what's wrong here? I'm not getting any error.

Also can you suggest a good example in getting CouchBase queryresult into a .net object.

Upvotes: 2

Views: 432

Answers (2)

Broodja
Broodja

Reputation: 11

Something like this (using Newtonsoft.Json.Linq):

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

Upvotes: 1

Mostafiz
Mostafiz

Reputation: 7352

Seems your json is not in correct format. If I say your json is like

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

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

Then create a model like

public class Document
{
   public UserDocument document {get;set;}
}

and change your UserDocument model's createdDate and processedDate properties as double because its like that in your 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; }

    }

and then deserialize

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

Upvotes: 4

Related Questions