我有几个 JObjects 从不同的地方返回,但具有所有相同的属性。我需要将它连接/合并到一个更大的 jObject 中。这是可能的,我将如何去做?
我希望它具有与单个对象相同的属性。例如。
jObject1 = { "data": [{"name": "foo","id": "1234" }]};
jObject2 = {"data": [{ "name": "foo2", "id": "5678" }]};
导致这样的事情。
jobject3 = { "data": [{ "name": "foo", "id": "1234"}, { "name": "foo2", "id": "5678" }]};
我正在用 C# 编码,到目前为止我唯一想到的就是这样的事情,这是无效的。不太确定如何开始,也无能为力。
jobject3 = jObject1.Concat(jObject2);
我正在尝试手动循环遍历每个对象并构建一个新对象。我想我很接近,但在添加第二项(oAlldepartment.Add)时不断收到错误消息,说“无法将属性添加到 Newtonsoft.Json.Linq.JObject。对象上已经存在同名的属性。”。
动态 dynObj = JsonConvert.DeserializeObject(people); foreach (var item in dynObj.data) { string id = item.id; 字符串名称 = item.name;
department = getdepartment(id);
JObject oDepartment = new JObject();
try
{
if (!String.IsNullOrEmpty(department))
oDepartment = JObject.Parse(department);
}
catch (Exception ex)
{
}
JArray departmentArray = new JArray();
if (oDepartment != null)
{
foreach (var x in oDepartment["data"].Children())
{
try
{
JObject departmentObject = new JObject();
((JObject)departmentObject).Add(new JProperty("name", x["name"]));
((JObject)departmentObject).Add(new JProperty("department", new JObject(new JProperty("name", x["department"]["name"]))));
((JObject)departmentObject).Add(new JProperty("hire_date", x["hire_date"]));
((JObject)departmentObject).Add(new JProperty("description", x["description"]));
departmentArray.Add(departmentObject);
}
catch (Exception ex)
{
}
((JObject)x).Add(new JProperty("itemtype", "post"));
}
try
{
oAlldepartment.Add(new JProperty("", new JArray(departmentArray)));
}
catch (Exception ex)
{
}
}
}
谢谢,
朗达