【问题标题】:Custom dynamic JSON Deserializing [duplicate]自定义动态 JSON 反序列化 [重复]
【发布时间】:2017-04-03 21:48:00
【问题描述】:

使用 C#,反序列化动态 JSON 对象的正确方法是什么(即:一些 JSON,其中单个键的类型可以在对象之间更改)?

例如,如果我有这个(完全有效的)JSON:

{
  "stuffs": [
    { "content": "abcd" },
    { "content": "efgh" },
    { "content": [
        "ijkl",
        "mnop"
    ]}
  ]
}

其中thing 可以是字符串或字符串数​​组,如果我定义了这些类,我该如何反序列化?

class ThingContainer {
  List<Thing> stuffs;
}

class Thing {
  List<string> content;
}

尝试反序列化我(预期)遇到异常:

Newtonsoft.Json.JsonSerializationException: '无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型 'System.Collections.Generic.List`1[DummyProject.东西]'

【问题讨论】:

标签: c# json json.net deserialization json-deserialization


【解决方案1】:

您的问题是您的 C# 类不能准确地表示 JSON。

您的 JSON 有一个对象,其中包含一个对象“stuffs”,它是一个对象列表,“content”是一个字符串列表。

您在 C# 类中拥有的是一个对象,其中包含一个字符串列表对象。

您需要一个包含一个对象的对象,该对象是一个包含字符串列表的对象列表。

试试这个:

public class Content
{
    public List<string> Content { get; set; }
}

public class Stuff
{
    public List<Content> Contents { get; set; }
}

public class ThingContainer
{
    public List<Stuff> Stuffs { get; set; }
}

【讨论】:

  • 这不适用于示例数组中的最后一个条件/条目,也许是自定义格式化程序/反序列化程序,即使它是平面结构中的一项,也会反序列化为列表?
  • 我注意到最后一个要求是列表并更新了我的回复。
【解决方案2】:

我不知道 C# 中是否有任何解决方案,但我建议您调整您的 JSON 结构,例如:

{
  arrayStuffs[
    { content: ['123', '456'] },
    // another arrays...
  ],
  stringStuffs{
    content: '',
    // another strings..
  },
  // another stuffs, and so on
}

并为你所有的东西定义一个模型:

public class arrayStuff{
  List<string> content;
}

【讨论】:

    【解决方案3】:

    我不确定 NewtonSoft 是否可以做到这一点,但如果您回到 Windows.Data.Json 中的内置 API,您可以获得所需的任何灵活性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-14
      • 1970-01-01
      • 1970-01-01
      • 2017-01-30
      • 2011-04-12
      • 2013-01-18
      • 2014-08-02
      • 2022-09-23
      相关资源
      最近更新 更多