【发布时间】:2020-05-31 05:10:02
【问题描述】:
我需要将一个嵌套列表集合缩减为另一个。我只需要保留具有参数 IsOk == true 的对象。
public class Item {
public string Id { get; set; }
public Item[] Items { get; set; }
public bool IsOk { get; set; }
这是输入json:
{
'id': '1',
'isOk': false,
'items': [
{
'id': '21',
'isOk': false,
'items': [
{
'id': '31',
'isOk': true,
'items': [
{
'id': '41',
'isOk': true,
'items': null
},
{
'id': '42',
'isOk': true,
'items': null
}
]
}
]
},
{
'id': '22',
'isOk': true,
'items': [
{
'id': '32',
'isOk': true,
'items': [
{
'id': '43',
'isOk': true,
'items': null
},
{
'id': '44',
'isOk': true,
'items': null
}
]
}
]
}
]
}
这是正确的修改后的 json。
[
{
'id': '31',
'isOk': true,
'items': [
{
'id': '41',
'isOk': true,
'items': null
},
{
'id': '42',
'isOk': true,
'items': null
}
]
},
{
'id': '22',
'isOk': true,
'items': [
{
'id': '32',
'isOk': true,
'items': [
{
'id': '43',
'isOk': true,
'items': null
},
{
'id': '44',
'isOk': true,
'items': null
}
]
}
]
}
]
如你所见,新的 json 修改了层次结构,只保留属性 IsOk == true 的对象。 对我来说最大的问题是如何改变对象的层次结构。 目前我尝试使用递归函数,但也许更好的是使用while循环?
【问题讨论】:
-
您是否使用标准 JSON 解析库将 JSON 解析为 C# 对象?例如。 stackoverflow.com/questions/6620165/how-can-i-parse-json-with-c
-
这只是结果应该是什么样子的示例。我只有第一个 json,我需要构建对象以将其序列化为第二个 json。
-
听起来你想先展平你的结构,然后只得到那些'IsOk'。如果是这样,这个答案建议使用LINQ-to-JSON我的帮助。
-
但是我怎样才能保留最后一个可用的父级
-
这应该是树的数据结构吗?是否允许两个以上的项目作为一个项目的后代?您当前所要求的根本不是微不足道的,因为层次结构的更改也会导致数据结构的更改(想象 ID=1 的 Item 作为树的根节点,如果您在不替换的情况下将其删除你没有一棵树了,但有两棵)。我的意思是,这可以解决,但不仅仅是通过反序列化 json 并且不使用合适的数据结构(可能是二叉搜索树?)。