Animesh D
Animesh D

Reputation: 5002

Unexpected token error when using Json.NET

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.

Upvotes: 1

Views: 6758

Answers (1)

Lloyd
Lloyd

Reputation: 29668

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.

Upvotes: 4

Related Questions