1

I am following the official example of parsing JSON with .NET.

I created a products.json file:

{
    "Name": "Apple",
    "Expiry": new Date(1230422400000),
    "Price": 3.99,
    "Sizes": [
        "Small",
        "Medium",
        "Large"
    ]
}

to read it into a string and then deserialize it. I am trying to parse it as follows:

Product deserializedProduct;

string jsonObj = File.ReadAllText(@"..\..\Content\products.json");
if (jsonObj != null) 
{
    try
    {
        deserializedProduct = JsonConvert.DeserializeObject<Product>(jsonObj);
    }
    catch (Exception e)
    {
        //log exception;
    }
}

I get the following exception:

Error reading date. Unexpected token: StartConstructor. Path 'Expiry', line 3, position 24.

I know JSON doesn't allow date objects, but why does the example use the new Date(1230422400000) for representing a date object.

1 Answer 1

4

You need to pass in a converter. Try something like this:

deserializedProduct = JsonConvert.DeserializeObject<Product>(jsonObj, new JavaScriptDateTimeConverter());

As to why, it could be an old example, Json.NET used to use the old Date object before using the more formal way (IIRC). However it can both serialize and deserialize still if you tell it how to handle it.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. This worked. I just had to include Newtonsoft.Json.Converters namespace.
Ahh sweet I'll keep that in mind. I guess it defaults to all converters :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.