【发布时间】:2021-06-06 18:44:21
【问题描述】:
您好,我需要将 json 序列化结果的内容展平,但我不知道如何,我尝试了不同的方法,但没有成功,这是一个示例:
(为了简单起见,我使用 NET 5 记录与使用类相同)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
namespace dicttest
{
public class Program
{
public record inventory(int inventoryID, string name, string description);
public record aditionals(int inventoryID, string name, string value);
public static List<inventory> inventoryList = new();
public static List<aditionals> inventoryAditionalList = new();
public static void Main()
{
// populate
inventoryList.Add(new inventory(1, "Inventory 1", "Inventory 1 cool description"));
inventoryList.Add(new inventory(2, "Inventory 2", "Inventory 2 cool description"));
inventoryList.Add(new inventory(3, "Inventory 3", "Inventory 3 cool description"));
inventoryAditionalList.Add(new aditionals(1, "legs", "4"));
inventoryAditionalList.Add(new aditionals(1, "screws", "20"));
inventoryAditionalList.Add(new aditionals(2, "legs", "3"));
inventoryAditionalList.Add(new aditionals(3, "screws", "50"));
// join
var result = inventoryList.Select(c => new
{
c.inventoryID,
c.name,
c.description,
aditionals = inventoryAditionalList.Where(s => s.inventoryID == c.inventoryID).Select(d => new { d.name, d.value })
});
// show
var json3 = JsonSerializer.Serialize(result, new JsonSerializerOptions { WriteIndented = true });
Console.WriteLine(json3);
}
}
}
这是该代码的结果:
[
{
"inventoryID": 1,
"name": "Inventory 1",
"description": "Inventory 1 cool description",
"aditionals": [
{
"name": "legs",
"value": "4"
},
{
"name": "screws",
"value": "20"
}
]
},
{
"inventoryID": 2,
"name": "Inventory 2",
"description": "Inventory 2 cool description",
"aditionals": [
{
"name": "legs",
"value": "3"
}
]
},
{
"inventoryID": 2,
"name": "Inventory 3",
"description": "Inventory 3 cool description",
"aditionals": [
{
"name": "screws",
"value": "50"
}
]
}
]
但这是我想要得到的:
[
{
"inventoryID": 1,
"name": "Inventory 1",
"description": "Inventory 1 cool description",
"legs": "4",
"screws": "20"
},
{
"inventoryID": 2,
"name": "Inventory 2",
"description": "Inventory 2 cool description",
"legs": "3"
},
{
"inventoryID": 3,
"name": "Inventory 3",
"description": "Inventory 3 cool description",
"screws": "50"
}
]
有什么想法吗?谢谢!
【问题讨论】:
-
你了解
.SelectMany()吗? -
是的,但在这种情况下我无法使用它
-
我试过了,但我做不到,我不知道为什么
-
“无法做到”并不是对您所面临问题的具体描述。
-
我的意思是,我做到了,但有更好的方法可以告诉我。