如何使用 Newtonsoft JSON.NET 将 JSON 反序列化为 IEnumerable

2024-04-15

给定这个 JSON:

[
  {
    "$id": "1",
    "$type": "MyAssembly.ClassA, MyAssembly",
    "Email": "[email protected] /cdn-cgi/l/email-protection",
  },
  {
    "$id": "2",
    "$type": "MyAssembly.ClassB, MyAssembly",
    "Email": "[email protected] /cdn-cgi/l/email-protection",
  }
]

和这些课程:

public abstract class BaseClass
{
    public string Email;
}
public class ClassA : BaseClass
{
}
public class ClassB : BaseClass
{
}

如何将 JSON 反序列化为:

IEnumerable<BaseClass> deserialized;

我不能使用JsonConvert.Deserialize<IEnumerable<BaseClass>>()因为它抱怨说BaseClass是抽象的。


你需要:

JsonSerializerSettings settings = new JsonSerializerSettings
{
    TypeNameHandling = TypeNameHandling.All
};

string strJson = JsonConvert.SerializeObject(instance, settings);

所以 JSON 看起来像这样:

{
  "$type": "System.Collections.Generic.List`1[[MyAssembly.BaseClass, MyAssembly]], mscorlib",
  "$values": [
    {
      "$id": "1",
      "$type": "MyAssembly.ClassA, MyAssembly",
      "Email": "[email protected] /cdn-cgi/l/email-protection",
    },
    {
      "$id": "2",
      "$type": "MyAssembly.ClassB, MyAssembly",
      "Email": "[email protected] /cdn-cgi/l/email-protection",
    }
  ]
}

然后你可以反序列化它:

BaseClass obj = JsonConvert.DeserializeObject<BaseClass>(strJson, settings);

文档:类型名称处理设置 http://www.newtonsoft.com/json/help/html/SerializeTypeNameHandling.htm

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Newtonsoft JSON.NET 将 JSON 反序列化为 IEnumerable 的相关文章

随机推荐