我正在尝试将一些数据从一种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服务回复。 / p>
我使用c#作为中间层。
答案 0 :(得分:0)
您可以按照 json.net 中所示安装How to install JSON.NET using NuGet?然后使用LINQ to JSON解析和转换输入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小提琴here。
注意:
我最初反序列化为JObject [][]
以确保输入实际上是一个对象数组的数组。
最初反序列化为KeyValuePair<string, JToken> [][]
也有效,如图here所示。