Using Newtonsoft to Deserialize a Date Stamp That Might Consist Only of a Year

Using Newtonsoft to deserialize a Date Stamp that might consist only of a year

when deserializing,

Deserialize the Year as an int and add another property that returns the full date.

something like:

public class MyObject
{
[JsonProperty("year")]
public int Year { get; set; }

[JsonIgnore]
public DateTime FullDate() {
return new DateTime (this.Year, 1, 1, 0, 0, 0);
}
}

Using Newtonsoft to deserialize a Date Stamp that might consist only of a year

when deserializing,

Deserialize the Year as an int and add another property that returns the full date.

something like:

public class MyObject
{
[JsonProperty("year")]
public int Year { get; set; }

[JsonIgnore]
public DateTime FullDate() {
return new DateTime (this.Year, 1, 1, 0, 0, 0);
}
}

Using Newtonsoft JToken.ToObject<T> to deserializeNodaTime Instant

Per the Noda Time User Guide:

  • Install the NodaTime.Serialization.JsonNet nuget package
  • Call ConfigureForNodaTime on your JsonSerializerSettings

If you're still getting "Unexpected token..." messages, then likely you have changed the DateParseHandling setting. The ConfigureForNodaTime call will set this to DateParseHandling.None, and it should be left that way.

Note that this works well with the JsonConvert.SerializeObject and JsonConvert.DeserializeObject classes, as they accept a JsonSettings parameter, which can also be set via JsonConvert.DefaultSettings. Here is a live demo using this approach.

However, if you're using the JObject APIs, there is one slight problem. JObject.Parse has no ability to take a settings parameter, and by default you won't have the DateParseHandling.None that is required at this stage. The solution to this involves using a JsonTextReader, and is described well in this StackOverflow answer.

Keep the order of the JSON keys during JSON conversion to CSV

Solved.

I used the JSON.simple library from here https://code.google.com/p/json-simple/ to read the JSON string to keep the order of keys and use JavaCSV library from here http://sourceforge.net/projects/javacsv/ to convert to CSV format.



Related Topics



Leave a reply



Submit