要将第一个JSON样例转换为第二个JSON样例,可以使用LINQ to JSON,如下所示:
// Parse (or load from a stream) the incoming JSON as a JArray
var array = JArray.Parse(jsonString);
// For each object in the array, query they Key/Value properties of each Fields[*] object and turn then into a single JPropery,
// then add those properties to a new JObject
var query = array.Select(i =>
new JObject(i.SelectTokens("Fields[*]").Select(o => new JProperty((string)o["Key"], o["Value"]))));
// Create a new JArray from the query
var newArray = new JArray(query);
最棘手的部分在这里:
i => new JObject(i.SelectTokens("Fields[*]").Select(o =>
new JProperty((string)o["Key"], o["Value"])))
该表达式如下:
- 使用
SelectTokens()
查询根数组项中的所有Fields[*]
个对象;
- 然后获取每个对象的
"Key"
和"Value"
个属性;
- 然后把它们变成一个单独的
JProperty
;
- 并最终将这
JProperty
个实例组合成单个JObject
个.
请注意,如果这[*].Fields[*].Key
个属性中的一个属性丢失,上面的代码将抛出异常,因此您可能需要判断一下.
演示小提琴#1here.
同样,要将第二个样本转换为第一个样本,您可以执行以下操作:
var query = array
.OfType<JObject>()
.Select(o =>
new JObject
{
{"Fields", new JArray(o.Properties().Select(p => new JObject{{"Key", p.Name}, {"Value", p.Value}}))},
});
var newArray = new JArray(query);
这里我使用C#的S dictionary collection initializer syntax来初始化我的JObject
个实例,我可以这样做,因为JObject
实现了IDictionary<string, JToken>
.
here. history of life