gpt4 book ai didi

c# - 来自数据表和 IList 的嵌套 JSON

转载 作者:太空宇宙 更新时间:2023-11-03 14:47:05 25 4
gpt4 key购买 nike

我有两个变量

Datatable listOfObject

正在生成如下所示的 JSON

"listofObject" : [
{
"Obj1": "Some String Value",
"Obj2": "Some Date Value",
"Obj3": "Some Int Value",
"Obj4": "Some Date Value",
....
}
]

和另一个对象

IList<Class> ObjectInfo

正在生成如下所示的 JSON

"ObjectInfo" : [
{
"name" : "Obj1",
"Style" : "Style Name",
"Data Type" : "String"
},
{
"name" : "Obj2",
"Style" : "Style Name",
"Data Type" : "Date"
},
{
"name" : "Obj3",
"Style" : "Style Name",
"Data Type" : "Int"
},
.....
]

我怎样才能将它们组合成如下所示的 JSON 结构

"finalStructure" :[
"Obj1": {
"Style" : "Style Name",
"Data Type" : "String"
},
"Obj2": {
"Style" : "Style Name",
"Data Type" : "Date"
},
"Obj3": {
"Style" : "Style Name",
"Data Type" : "Int"
},
....
]

最佳答案

从数据表中,您有一个 IEnumerable<IDictionary<string, string>> ,所以你要做的是首先创建一个查找,然后你可以安全地投影你的结果:

var items = listOfObjects.FromJson<IEnumerable<IDictionary<string, string>>>();

var info = objectInfo.FromJson<IEnumerable<IDictionary<string, string>>>()
.ToLookup(it => it.Single(k => k.Key == "name").Value, it => it.Where(k => k.Key != "name"));

var restructured = items
.SelectMany(it => it.Keys)
.GroupBy(it => it)
.Select(it => new
{
Key = it.Key,
Value = info[it.Key].SelectMany(fo => fo).ToDictionary(fo => fo.Key, fo => fo.Value)
})
.ToDictionary(it => it.Key, it => it.Value);

// extension method with NewtonSoft.JSON.net
public static T FromJson<T>(this string json)
{
var serializer = new JsonSerializer();
using (var sr = new StringReader(json))
using (var jr = new JsonTextReader(sr))
{
var result = serializer.Deserialize<T>(jr);
return result;
}
}

关于c# - 来自数据表和 IList 的嵌套 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53720259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com