2

I am using Newtonsoft.Json library to parse JSON message in c#

string json = @"{'SomeSchedule': [ { 'PeriodEnd': '2014-05-28', 'PeriodStart': '2014-02-28', 'ResetDate': '2014-05-26', 'PayDate': '2014-05-28' }, { 'PeriodEnd': '2014-02-28', 'PeriodStart': '2013-11-29', 'ResetDate': '2014-02-26', 'PayDate': '2014-02-28' }, { 'PeriodEnd': '2014-12-01', 'PeriodStart': '2014-08-28', 'ResetDate': '2014-11-26', 'PayDate': '2014-12-01' }, { 'PeriodEnd': '2014-08-28', 'PeriodStart': '2014-05-28', 'ResetDate': '2014-08-26', 'PayDate': '2014-08-28' } ], }"; 

Data class:

 public class Data { public DateTime PeriodEndDate { get; set; } public DateTime PeriodStartDate { get; set; } public DateTime ResetDate { get; set; } public DateTime PayDate { get; set; } } 

Parsing

 JObject dataObject1 = JObject.Parse(json); var plan = dataObject1["SomeSchedule"].ToObject<IList<Data>>(); 

I'm not able to read all DateTime fields correctly. When the above code is run, we can see the value in plan variable. I'm able to read ResetDate and PayDate, but PeriodEnd and PeriodStart are not read correctly. It is returning a default date "1/1/0001".

Can anyone please let me know what i am doing wrong In above code?

1 Answer 1

2

Change property names to match data in json:

public class Data { public DateTime PeriodEnd { get; set; } // instead of PeriodEndDate public DateTime PeriodStart { get; set; } // instead of PeriodStartDate public DateTime ResetDate { get; set; } public DateTime PayDate { get; set; } } 

Or use JsonProperty attribute to map your properties:

public class Data { [JsonProperty("PeriodEnd")] public DateTime PeriodEndDate { get; set; } [JsonProperty("PeriodStart")] public DateTime PeriodStartDate { get; set; } public DateTime ResetDate { get; set; } public DateTime PayDate { get; set; } } 
Sign up to request clarification or add additional context in comments.

1 Comment

ohh...OMG..how i haven't seen this. Thank you so much for your help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.