与json.net flatten nested json在C#中
我通过WebAPI收到JSON格式的材料清单,该WebAPI具有相应的层次结构。 层次结构或嵌套可以是任何深度。
材料清单如下所示:
{
"Quantity":0,
"QuantityUnit":"pcs",
"PartNumber":"12345",
"Parent":"",
"Children":[
{
"Quantity":1,
"QuantityUnit":"pcs",
"PartNumber":"88774",
"Parent":"12345",
"Children":[
{
"Quantity":1,
"QuantityUnit":"pcs",
"PartNumber":"42447",
"Parent":"88774"
},
{
"Quantity":0.420,
"QuantityUnit":"kg",
"PartNumber":"12387",
"Parent":"88774"
}
]
}
]
}
如何使用C#中的JSON.NET将此嵌套结构解析为一个简单的结构?
我想将其转换为:
[
{
"Quantity":0,
"QuantityUnit":"pcs",
"PartNumber":"12345",
"Parent":""
},
{
"Quantity":1,
"QuantityUnit":"pcs",
"PartNumber":"88774",
"Parent":"12345"
},
{
"Quantity":1,
"QuantityUnit":"pcs",
"PartNumber":"42447",
"Parent":"88774"
},
{
"Quantity":0.420,
"QuantityUnit":"kg",
"PartNumber":"12387",
"Parent":"88774"
}
]
对于避难所化,我使用以下类:
public class Bom
{
public class TopLevel
{
public double Quantity { get; set; }
public string QuantityUnit { get; set; }
public string PartNumber { get; set; }
public string Parent { get; set; }
public List<Item> Children { get; set; }
}
public class Item
{
public double Quantity { get; set; }
public string QuantityUnit { get; set; }
public string PartNumber { get; set; }
public string Parent { get; set; }
}
public double Quantity { get; set; }
public string QuantityUnit { get; set; }
public string PartNumber { get; set; }
public string Parent { get; set; }
public IList<TopLevel> Children { get; set; }
}
此外,我还使用此代码将JSON验证为对象:
Bom bom = JsonConvert.DeserializeObject<Bom>(File.ReadAllText(jsonPath));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,让我们定义映射器
children
属性接下来,让我们定义一个递归功能以累积
jobign s
,最后让我们使用它们
toString
在累加器上调用
将返回此更新#1
如果您的源JSON包含深层层次结构(假设超过5个级别),则
DeepClone
并不是真正有效的,因为您要复制整个子树。要解决此问题,您只需要重写
MAP
函数First let's define a mapper
Children
propertyNext let's define a recursive function to accumulate the
JObject
sAnd finally let's make use of them
The
ToString
call on theaccumulator
will return thisUPDATE #1
If your source json contains a deep hierarchy (lets say more than 5 levels) then the
DeepClone
is not really efficient, since you are copying the whole subtree.To fix this problem you just need to rewrite the
Map
function应对原始列表进行挑选,用 enumerable.selectmany ,并序列化结果序列。
Deserialize the original list, flatten it with Enumerable.SelectMany, and serialize the resulting sequence.