C# 如何转换动态JSON

C# 如何转换动态JSON,c#,json,json.net,C#,Json,Json.net,我试图将一些数据从一种JSON格式转换为另一种JSON格式,但遇到了一些问题 [ [{"Key":"entity_id","Value":"1"},{"Key":"CustomerName","Value":"Test1"},{"Key":"AccountNumber","Value":"ACC17-001"},{"Key":"CustomerType","Value":"Direct Sale"}], [{"Key":"entity_id","Value":"2"},{"Key":"Custo

我试图将一些数据从一种JSON格式转换为另一种JSON格式,但遇到了一些问题

[
[{"Key":"entity_id","Value":"1"},{"Key":"CustomerName","Value":"Test1"},{"Key":"AccountNumber","Value":"ACC17-001"},{"Key":"CustomerType","Value":"Direct Sale"}],
[{"Key":"entity_id","Value":"2"},{"Key":"CustomerName","Value":"Test2"},{"Key":"AccountNumber","Value":"ACC17-002"},{"Key":"CustomerType","Value":"Direct Sale"}],
[{"Key":"entity_id","Value":"3"},{"Key":"CustomerName","Value":"Test3"},{"Key":"AccountNumber","Value":"ACC17-003"},{"Key":"CustomerType","Value":"Direct Sale"}],
[{"Key":"entity_id","Value":"4"},{"Key":"CustomerName","Value":"Test4"},{"Key":"AccountNumber","Value":"ACC17-004"},{"Key":"CustomerType","Value":"Direct Sale"}],
[{"Key":"entity_id","Value":"5"},{"Key":"CustomerName","Value":"Test5"},{"Key":"AccountNumber","Value":"ACC17-005"},{"Key":"CustomerType","Value":"Invoice"}],
[{"Key":"entity_id","Value":"6"},{"Key":"CustomerName","Value":"Test6"},{"Key":"AccountNumber","Value":"ACC17-006"},{"Key":"CustomerType","Value":"Invoice"}]
]
为此:

[
{"entity_id":"1","CustomerName":"Test1","AccountNumber":"ACC17-001","CustomerType":"Direct Sale"},
{"entity_id":"2","CustomerName":"Test2","AccountNumber":"ACC17-002","CustomerType":"Direct Sale"},
{"entity_id":"3","CustomerName":"Test3","AccountNumber":"ACC17-003","CustomerType":"Direct Sale"},
{"entity_id":"4","CustomerName":"Test4","AccountNumber":"ACC17-004","CustomerType":"Direct Sale"},
{"entity_id":"5","CustomerName":"Test5","AccountNumber":"ACC17-005","CustomerType":"Invoice"},
{"entity_id":"6","CustomerName":"Test6","AccountNumber":"ACC17-006","CustomerType":"Invoice"}
]
第一个数据源是一个动态sql查询……我需要生成一个自定义对象,将该sql查询的列作为该对象的属性,然后将其编码为JSON,以便Web服务进行回复


我使用c作为中间层。

您可以执行所需的转换,方法是按照中所示进行安装,然后使用解析和转换您的输入JSON,而无需对当前的精确键和值做任何假设

如果inputJson是从SQL查询中接收到的JSON字符串,则以下代码执行此任务:

// Deserialize the input JSON as an array of arrays of JSON objects
var inputArray = JsonConvert.DeserializeObject<JObject [][]>(inputJson);

// Convert each inner array to a JSON object whose property names come from the nested objects' Key values and property values come from the nested objects' Value values:
var outputArray = inputArray.Select(a => new JObject(a.Select(o => (new JProperty((string)o["Key"], o["Value"])))));

// And re-serialize to JSON.
var outputJson = JsonConvert.SerializeObject(outputArray, Formatting.Indented);
示例工作.Net小提琴

注:

我最初反序列化到一个JObject[]],以确保输入实际上是一个对象数组

最初反序列化到KeyValuePair[]]也可以工作,如图所示