我需要转换以下JSON数组:
[{
"ID": 2,
"NAME": "name_1",
"UUID": "something"
}, {
"ID": 3,
"NAME": "name_2",
"UUID": "something-else"
}]
放入这样的JSON数组中:
[{
"ATTRIBUTE": "ID",
"EXAMPLE_1": "2",
"EXAMPLE_2": "3"
}, {
"ATTRIBUTE": "NAME",
"EXAMPLE_1": "name_1",
"EXAMPLE_2": "name_2"
}, {
"ATTRIBUTE": "UUID",
"EXAMPLE_1": "something",
"EXAMPLE_2": "something-else"
}
如您所见,我需要第一个数组中的键是第二个数组中的值,我只想获取一次。第一次迭代后,我希望将一个值附加到对象上,但是我需要通过ATTRIBUTE值找到该对象。
我对C#相当陌生,但我打算使用JSON.NET
答案 0 :(得分:0)
要实现所需的功能,可以序列化一个Dictionary
对象列表,其中包含要包含的模型每个属性的值。
例如:
//this is the List that you will use to produce the expected JSON format
List<Dictionary<string, object>> values = new List<Dictionary<string, object>>();
//setup a Dictionary for every property you want to include
Dictionary<string, object> ids = new Dictionary<string, object>();
ids.Add("Attribute", "Id");
for(int i = 0; i < examples.Count; i++)
ids.Add("Example_" + (i + 1).ToString(), examples[i].Id);
//add the dictionary to the list to be included in the JSON
values.Add(ids);
//serialize
string json = JsonConvert.SerializeObject(values);
还有其他方法来填充Dictionary
对象的列表,例如使用反射,但这只是为了演示这种想法。
this fiddle中的完整示例。
HTH
答案 1 :(得分:0)
如果要使用 Linq 完成此操作,则可以使用以下内容。
var json = @" [{
'ID': 2,
'NAME': 'name_1',
'UUID': 'something'
}, {
'ID': 3,
'NAME': 'name_2',
'UUID': 'something-else'
}]";
var newData = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(json)
.SelectMany(x=> x.Select(c=>new {c.Key,c.Value}))
.GroupBy(x=>x.Key)
.Select(x=> (new List<KeyValuePair<string,string>>{new KeyValuePair<string,string>("ATTRIBUTE",x.Key)}
.Union(x.ToList().Select((f,index)=> new KeyValuePair<string,string>($"EXAMPLE_{index+1}",f.Value)).ToList())))
.Select(x=>x.ToDictionary(c=>c.Key,c=>c.Value));
var newDataSerialized = JsonConvert.SerializeObject(newData);
输出
[
{
"ATTRIBUTE": "ID",
"EXAMPLE_1": "2",
"EXAMPLE_2": "3"
},
{
"ATTRIBUTE": "NAME",
"EXAMPLE_1": "name_1",
"EXAMPLE_2": "name_2"
},
{
"ATTRIBUTE": "UUID",
"EXAMPLE_1": "something",
"EXAMPLE_2": "something-else"
}
]