合并具有相同属性值的json对象c#
Posted
技术标签:
【中文标题】合并具有相同属性值的json对象c#【英文标题】:Merge json objects that with the same value of property c# 【发布时间】:2021-03-22 11:38:02 【问题描述】:如何在具有相同键和值的同一响应中组合 JSON 对象。就像我有两个具有相同语言的对象:Python 我想将它们组合起来并列出该语言下的剩余数据 Python 我不希望它被重复
[
[
"language": "Python",
"id": 319029846,
"full_Name": "beurtschipper/Depix",
"name": "Depix"
,
"language": "Python",
"id": 319169382,
"full_Name": "benwilber/boltstream",
"name": "boltstream"
,
"language": "Python",
"id": 316899719,
"full_Name": "r0ysue/r0capture",
"name": "r0capture"
],
[
"language": "YARA",
"id": 318029147,
"full_Name": "fireeye/red_team_tool_countermeasures",
"name": "red_team_tool_countermeasures"
],
[
"language": "TypeScript",
"id": 313443335,
"full_Name": "pmndrs/valtio",
"name": "valtio"
]
]
我想要的形式是什么
[
[
"language": "Python",
"id": [319029846, 319169382, 316899719],
"full_Name": ["beurtschipper/Depix", "benwilber/boltstream", "r0ysue/r0capture"],
"name": ["Depix", "boltstream", "r0capture"]
],
[
"language": "YARA",
"id": 318029147,
"full_Name": "fireeye/red_team_tool_countermeasures",
"name": "red_team_tool_countermeasures"
],
[
"language": "TypeScript",
"id": 313443335,
"full_Name": "pmndrs/valtio",
"name": "valtio"
]
]
这是我正在使用的代码
public class Items
[JsonPropertyName("language")]
public string Language get; set;
[JsonPropertyName("id")]
public int Id get; set;
[JsonPropertyName("name")]
public string Name get; set;
[JsonPropertyName("full_name")]
public string Full_Name get; set;
public string total_count get; set;
public class Root
[JsonPropertyName("items")]
public List<Items> Items get; set;
Root jObj2 = JsonConvert.DeserializeObject<Root>(readerResult);
var result = jObj2.Items.Select(x => new
x.Language,
x.Id,
x.Full_Name,
x.Name
).GroupBy(x => x.Language).ToArray();
return new JsonResult(result);
【问题讨论】:
【参考方案1】:GroupBy
是一个很好的起点。获得组后,您需要将每个组的各个属性选择到一个新列表中:
var result = jObj2.Items
.GroupBy(x => x.Language)
.Select(group => new
Language = group.Key,
Ids = group.Select(x => x.Id).ToList(),
FullNames = group.Select(x => x.Full_Name).ToList(),
Names = group.Select(x => x.Name).ToList()
)
.ToArray();
【讨论】:
哦,先生,我为这很容易感到羞愧,除非我尝试将这些 ID、名称..etc 列在Ids = group.Select(x => x.Id).ToList(),
列表中,但我遇到了它们不是列表,我即使我应该在 Select 之前使用 GroupBy,但现在我有点知道 GroupBy 是如何工作的。如果你不介意我会问另一个问题.. 要知道的东西是经验还是我学得不好?当然非常感谢您的帮助。
你使用 Linq 的次数越多,你就越容易找到这类任务以上是关于合并具有相同属性值的json对象c#的主要内容,如果未能解决你的问题,请参考以下文章
如何将具有不同值的相同 JSON 对象反序列化为 java 类
使用角度js将具有相同ID的重复对象从json数据合并为单个对象