0

I am dynamically deserializing Json strings and I want to have them convert into their appropriate types upon deserializing, but since it's dynamic I don't necessarily know what they will become. For example I might have a Json that looks like this:

string serializedJsonString = { 
                                 "stringValue": "someString",
                                 "dateTimeObject": "2016-12-08" 
                              };

I want this Json to be deserialized into their key-value pairs, but their values stored as their appropriate object types, in the example above as String and DateTime.

I've tried some of the following like:

IDictionary<string, object> blah = new JavaScriptSerializer().Deserialize<IDictionary<string, object>>(serializedJsonString);

And:

dynamic blah = Json.Decode(serializedJsonString);

But it always just converts the "dateTimeObject" to a string. I've been told deserializing the Json can do this conversion, but I can't figure out how. What am I doing wrong?

keenns
  • 863
  • 4
  • 14
  • 26

1 Answers1

0

Please also read one of my previous answers. It explains how to deal with dictionary keyvalue pairs regarding JSON.

Then the DateTime part: DateTimes in JSON are hard.

The problem comes from the JSON spec itself: there is no literal syntax for dates in JSON. The spec has objects, arrays, strings, integers, and floats, but it defines no standard for what a date looks like.

With no standard for dates in JSON, the number of possible different formats when interoping with other systems is endless.

You need to use a JsonConverter to override how a type is (de)serialized.

public class MyDateTimeConvertor : DateTimeConverterBase
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return DateTime.Parse(reader.Value.ToString());
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue( ((DateTime)value).ToString("dd/MM/yyyy") );
    }
}
Community
  • 1
  • 1