首页 > 解决方案 > 如何使用 Newtonsoft JSON 有条件地输出列表或字典字符串?

问题描述

public class MyClass
{
    public string SomeProperty { get; set; }
    public List<ChildClass> Items { get; set; }
}

public class ChildClass
{
    public string IDProperty { get; set; }
    public string SomeOtherProperty { get; set; }

}

我正在使用 NewtonSoft (12) 将本质上是上述定义的对象写入 JSON 字符串的对象,但取决于我调用的方法,我希望JObject.FromObject(MyClassInstance)将子项输出为 JSON 数组,有时作为JSON 字典(IDProperty用作字典键)。

我尝试使用 aJsonConverter并且能够使用该WriteJson方法以两种方式输出(通过在使用 序列化之前将列表转换为字典或数组serializer.Serialize(writer, value))但我无法弄清楚如何“告诉”JsonConverter 选择哪种方式正如我所说JObject.FromObject(MyClassInstance)。我最好的猜测是在我在 FromObject 中传递的序列化程序中传递一个参数,但我无法找到传递该信息的地方。

因此,要清楚,在不更改 Class 属性本身的情况下,我希望能够在输出之间切换:

{
  "SomeProperty": "myID",
  "Items": [
    {
      "cc1IDProperty": "1",
      "SomeOtherProperty": "2"
    },
    {
      "cc1IDProperty": "2",
      "SomeOtherProperty": "4"
    }
  ]
}

{
  "SomeProperty": "myID",
  "Items": {
    "1": {
      "cc1IDProperty": "1",
      "SomeOtherProperty": "2"
    },
    "2": {
      "cc1IDProperty": "2",
      "SomeOtherProperty": "4"
    }
  }
}

标签: c#json.net.net-standard-2.0

解决方案


推荐阅读