user2185592
user2185592

Reputation: 388

Json deserialization fails

I have following json string which I receive from API call :

"\"{\\r\\n  \\\"Table\\\": [\\r\\n    {\\r\\n      \\\"MaxDate\\\": \\\"2019-06-09T00:00:00\\\",\\r\\n      \\\"MinDate\\\": \\\"2019-01-26T00:00:00\\\"\\r\\n    }\\r\\n  ]\\r\\n}\""

I want to deserialize this string to following class structure

    public class Dates
    {
        public DateTime MaxDate { get; set; }

        public DateTime MinDate { get; set; }
    }

    public class TableResult
    {
        public List<Dates> Table { get; set; }
    }

When I try to deserialize this json string to above class using Newtonsoft's Jsonconvert,

 JsonConvert.DeserializeObject<TableResult>(result);

it throws exception

Error converting value "{
  "Table": [
{
  "MaxDate": "2019-06-09T00:00:00",
  "MinDate": "2019-01-26T00:00:00"
}
 ]}" to type 'API_Test.Program+TableResult'. Path '', line 1, position 144.

I tried removing the spaces and \r\n from the string but still it throws exception and fails to deserialize.

Can anyone help to figure out what is wrong I'm doing?

Edit 1 :

String which I get from the API is shown in image below : enter image description here

Edit 2 : I have updated the original json string

Upvotes: 2

Views: 6289

Answers (1)

JohanP
JohanP

Reputation: 5472

Your API is returning a string that represents json as a string. So you first need to deserialize to string and then deserialize that to your TableResult

var json = "\"{\\r\\n  \\\"Table\\\": [\\r\\n    {\\r\\n      \\\"MaxDate\\\": \\\"2019-06-09T00:00:00\\\",\\r\\n      \\\"MinDate\\\": \\\"2019-01-26T00:00:00\\\"\\r\\n    }\\r\\n  ]\\r\\n}\"";

var str = JsonConvert.DeserializeObject<string>(json);
var test = JsonConvert.DeserializeObject<TableResult>(str);

Upvotes: 4

Related Questions