Json deserialization fails

僤鯓⒐⒋嵵緔 提交于 2020-01-15 10:11:13

问题


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 :

Edit 2 : I have updated the original json string


回答1:


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);


来源:https://stackoverflow.com/questions/56053027/json-deserialization-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!