如何将字符串序列化为 JSON 并按其中一个值分组?

How to serialize a string into JSON and group by one of the values?

我目前正在使用 JsonConvert().SerialiseObject(dt) 将数据表序列化为 JSON 格式,看起来像 {"id": "123", "name": "xyz", "value": "a"},{"id": "234", "name": "xyz", "value": "a"},{"id": "789, "name": "x", "value": "b"}

我希望格式按值分组,例如:-

[
   {
      "value":"a",
      "members":[
         {
            "id":"123",
            "name":"xyz"
         },
         {
            "id":"234",
            "name":"xyz"
         }
      ]
   },
   {
      "value":"b",
      "members":[
         {
            "id":"789",
            "name":"x"
         }
      ]
   }
]

使用 newtonsoft 可以轻松实现吗?

您最好在序列化之前以所需格式获取数据。 例如:

using System;
using System.Linq;
using System.Text.Json;

var dataTable = new[]
{
    new { Id = 123, Name = "xyz", value = "a" },
    new { Id = 123, Name = "xyz", value = "a" },
    new { Id = 123, Name = "xyz", value = "b" },
};

var groupedByValue = dataTable
    .GroupBy(x => x.value)
    .Select(x => new
    {
        Value = x.Key,
        Members = x.Select(m => new
        {
            m.Id,
            m.Name
        })
    });

var json = JsonSerializer.Serialize(groupedByValue);

Console.WriteLine(json);