【发布时间】:2021-11-13 10:23:05
【问题描述】:
我收到一个包含多个嵌套属性的第三方 API 响应:
变体 1:
{
"Property1": {
"Property2A": {
"Key1": "1",
"Key2": "2",
"Key3": "3"
},
"Property2B": {
"Property3": {
"Key4": "A",
"Key5": "B",
"Key6": "C",
"Property4": {
"Property5": {
"Property6": [
{
"Key7": "1",
"Property7A": {
"X": "1"
},
"Property7B": {
"X": "2"
},
"Property7C": {
"X": "3"
}
},
{
"Property7D": {
"X": "INeedThisString"
}
}
]
}
}
}
}
}
}
我只需要值“INeedThisString”。
我能够通过合适的模型结构(通过将模型映射到 Json 文件生成)并使用以下声明来达到属性 "X": "INeedThisString" 的值:
Rootobject obj = JsonConvert.DeserializeObject<Rootobject>(MyJsonString);
string result = obj.Property1.Property2B.Property3.Property4.Property5.Property6[1].Property7D.X;
这是我的问题:
API 有时会发布此架构的变体,唯一的区别是 Property3 声明为数组,例如:
变体 2:
{
"Property1": {
"Property2A": {
"Key1": "1",
"Key2": "2",
"Key3": "3"
},
"Property2B": {
"Property3": [ //<-----
{
"Key4": "A",
"Key5": "B",
"Key6": "C",
"Property4": {
"Property5": {
"Property6": [
{
"Key7": "1",
"Property7A": {
"X": "1"
},
"Property7B": {
"X": "2"
},
"Property7C": {
"X": "3"
}
},
{
"Property7D": {
"X": "INeedThisString"
}
}
]
}
}
}
] //<-----
}
}
}
//<-----:添加 2x 用于说明目的。
显然,变体 1 和我当前的模型结构并未将 Property3 声明为数组。
问题:
什么是解决这个问题的优雅方法在预处理中不接触 Json(删除/替换)?
我是否应该实现一组替代模型并通过错误函数在这两个模型集之间切换?请注意,7A-7D 属性中的键都是相同的:"X"。
【问题讨论】: