You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Item类列表转换为指定结构的JSON格式?

需求描述

我有一个Item类实例组成的列表,类定义如下:

public class Item
{
    public string Name { get; set; }
    public string Value { get; set; }
}

列表示例元素(实际数量不限):

Item1 : Name=A / Value=1000
Item2 : Name=B / Value=2000

需要生成指定格式的JSON:

{
    "Date":"2023-11-19",
    "A":"1000",
    "B":"2000"
}

实现方案

方案1:使用Newtonsoft.Json(Json.NET)

通过JObject动态构建JSON结构:

  1. 初始化数据:
var items = new List<Item>
{
    new Item { Name = "A", Value = "1000" },
    new Item { Name = "B", Value = "2000" }
};
var targetDate = "2023-11-19";
  1. 构建并序列化JSON:
using Newtonsoft.Json.Linq;

var jsonObject = new JObject();
jsonObject.Add("Date", targetDate);

foreach (var item in items)
{
    jsonObject.Add(item.Name, item.Value);
}

var resultJson = jsonObject.ToString(Newtonsoft.Json.Formatting.Indented);

运行后resultJson即为目标格式的JSON字符串。

方案2:使用System.Text.Json(.NET Core/.NET 5+内置)

借助Dictionary<string, object>承载数据后序列化:

  1. 初始化数据:
var items = new List<Item>
{
    new Item { Name = "A", Value = "1000" },
    new Item { Name = "B", Value = "2000" }
};
var targetDate = "2023-11-19";
  1. 构建字典并序列化:
using System.Text.Json;

var dataDict = new Dictionary<string, object>
{
    ["Date"] = targetDate
};

foreach (var item in items)
{
    dataDict[item.Name] = item.Value;
}

var serializeOptions = new JsonSerializerOptions { WriteIndented = true };
var resultJson = JsonSerializer.Serialize(dataDict, serializeOptions);

此方法无需额外安装包,直接使用.NET内置库即可生成格式化后的目标JSON。

内容的提问来源于stack exchange,提问作者SajjadZare

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 05:45:10