简体   繁体   中英

JSON newtonsoft deserialization

I have to parse a Web API in the following format. Please be aware that I cannot change the format of the JSON. It will always come in in this format:

{
    "somethingone": "abc",
    "somethingtwo": "abcde-1234",
    "information": {
        "report": [{
                "a": "1",
                "b": "2",
                "c": "3"
            },
            {
                "a1": "1a",
                "b2": "2a",
                "c3": "3a"
            }, {
                "a1": "1b",
                "b2": "2b",
                "c3": "3b"
            },
        ]
    }
}

When I try to parse it in Newtonsoft, I get the following error message:

Cannot deserialize the current json object because(eg{"name":"value"}) into type because the type requires a json array (eg[1,2,3]) to deserialize correctly.

I have been trying to solve this issue for days, but cannot figure this out.

在此问题中,您可能会将json解析为类的列表,例如List<ClassName> ,则应排除List <>,因为传入的json中只有一个主对象

If your items in array of report is not fixed means these items are with count from 1 to N then declaring property for each of item is hard and your class objects structure become tedious.

So you need collect all your items in Dictionary so it can parse your items from number 1 to N.

These class object are suitable to your json.

class RootObj
{
    public string somethingone { get; set; }
    public string somethingtwo { get; set; }
    public Information information { get; set; }
}

class Information
{
    public Dictionary<string, string>[] report { get; set; }
}

And you can deserialize like

RootObj mainObj = JsonConvert.DeserializeObject<RootObj>(json);

Console.WriteLine("somethingone: " + mainObj.somethingone);
Console.WriteLine("somethingtwo: " + mainObj.somethingtwo);

foreach (Dictionary<string, string> report in mainObj.information.report)
{
    foreach (KeyValuePair<string, string> item in report)
    {
         string key = item.Key;
         string value = item.Value;

         Console.WriteLine(key + ": " + value);
    }
}

Console.ReadLine();

Output:

在此处输入图片说明

Live Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM