3

I have some attributes returned from a rest service that are served as an array of name-value pairs.

In some cases the value is a date expressed in universal sortable format: { "name": "Modification-Date", "value": "2017-11-13T15:15:13.968Z" }

When it gets parsed by the deserialiser, the value is identified as a date but given that the object the pair is deserialised into has type string for both name and value, the date is then converted to string and it loses precision: "13/11/2017 15:15:13"

This is easily visible by using a converter for the NameValue type.

if (reader.TokenType == JsonToken.StartObject)
{
    var item = JObject.Load(reader);

    return new NameValueFacet()
    {
        Name = item["name"].Value<string>(),
        Value = item["value"].Value<string>()
    };
}

item["value"].Type shows the type is Date.

How do I get to have Json.NET leave it as a string, "unparsed"?

Pinco Pallino
  • 916
  • 1
  • 6
  • 18
  • 4
    Setting reader.DateParseHandling = DateParseHandling.None; before calling JObject.Load(reader) solves the problem. Is there any way I can just specify a Json Attribute on my NameValue class' Value property to get the same result without having to use a converter? – Pinco Pallino Nov 17 '17 at 19:45
  • Please edit your question rather than putting that in a comment. –  Nov 17 '17 at 19:58
  • 4
    There is not an attribute for turning off date parsing on a single property, but you can turn it off globally by setting `DateParseHandling = DateParseHandling.None` in `JsonSerializerSettings` and passing the settings to `JsonConvert.DeserializeObject`. Fiddle: https://dotnetfiddle.net/1y1bXM – Brian Rogers Nov 18 '17 at 00:08
  • 1
    Related? [How to prevent a single object property from being converted to a DateTime when it is a string](https://stackoverflow.com/q/40632820/3744182). – dbc Nov 18 '17 at 01:47

1 Answers1

0

You can try with Newtonsoft. See below.

JsonConvert.DeserializeObject<your_object>(your_json, new IsoDateTimeConverter{ DateTimeFormat = "dd/MM/yyy" });