c# - 如何使用 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"
}
}
}
解决方案
推荐阅读
- vba - 尝试备份数据库后端时出现错误 70 权限被拒绝
- api - 获取相同媒体 URL 的 Rest Assured 中的代码 403 和 Postman 中的代码 200
- windows - 仅使用批处理脚本从右键单击上下文菜单中运行选定的文件?
- c# - 正则表达式获取偏移量c#
- android - 在会话中在 Android 中存储常见数据的最佳方式?
- ios - 如何让 iOS VoiceOver 在更改时读取文本元素(不是当前焦点)?
- ios - 如何以编程方式创建按钮操作
- php - php:会话在本地主机上工作,但在服务器上
- python - Django 3.1 应用程序中垂直堆叠的 Plotly 子图中第二个图中的数据未正确显示
- python - Plotly python:修复图中的一个条作为其他条的参考