【问题标题】:JSON newtonsoft deserializationJSON newtonsoft 反序列化
【发布时间】:2018-12-13 05:15:05
【问题描述】:

我必须解析以下格式的 Web API。请注意,我无法更改 JSON 的格式。它总是以这种格式出现:

{
    "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"
            },
        ]
    }
}

当我尝试在 Newtonsoft 中解析它时,我收到以下错误消息:

无法反序列化当前的 json 对象,因为(例如 {"name":"value"}) 转换为类型,因为该类型需要一个 json 数组(例如 [1,2,3])才能正确反序列化。

我几天来一直在尝试解决这个问题,但无法解决这个问题。

【问题讨论】:

标签: c# arrays json.net deserialization


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    如果 report 数组中的项目不固定意味着这些项目的计数从 1 到 N,那么为每个项目声明属性很困难,并且您的类对象结构变得乏味。

    因此,您需要在Dictionary 中收集您的所有物品,以便它可以解析您的物品从编号 1 到 N。

    这些类对象适合你的 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; }
    }
    

    你可以像这样反序列化

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

    输出:

    Live Demo

    【讨论】:

    • 我在您的新问题中看到您使用了我上面的答案代码。但永远不要回复我它是否解决了你的问题。无论如何,您的新问题是您需要的扩展方案,但如果我的回答对您有帮助,那么您可以通过单击答案左侧的勾号使其变为绿色来接受我的回答:)
    猜你喜欢
    • 2013-06-06
    • 2019-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多