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

如何在C#中将两个数组转换为单个JSON对象?

在C#中将两个等长数组合并为指定JSON对象

你可以通过将两个数组的元素一一配对,再序列化为JSON对象来实现需求,以下是两种常用JSON库的实现方式:

使用Newtonsoft.Json(Json.NET)

  1. 先通过NuGet安装Newtonsoft.Json包
  2. 示例代码:
using Newtonsoft.Json;
using System.Linq;

string[] array1 = { "a", "b", "c" };
int[] array2 = { 1, 2, 3 };

// 将两个数组元素配对成键值对,再转为字典
var keyValuePairs = array1.Zip(array2, (key, value) => new { key, value })
                          .ToDictionary(kv => kv.key, kv => kv.value);

// 序列化为带缩进的JSON字符串
string json = JsonConvert.SerializeObject(keyValuePairs, Formatting.Indented);
Console.WriteLine(json);

使用System.Text.Json(.NET Core 3.0+ 内置)

如果你的项目基于.NET Core 3.0及以上版本,可以直接使用内置的System.Text.Json:

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

string[] array1 = { "a", "b", "c" };
int[] array2 = { 1, 2, 3 };

var keyValuePairs = array1.Zip(array2, (key, value) => new { key, value })
                          .ToDictionary(kv => kv.key, kv => kv.value);

// 序列化为带缩进的JSON字符串
string json = JsonSerializer.Serialize(keyValuePairs, new JsonSerializerOptions { WriteIndented = true });
Console.WriteLine(json);

两种方式最终都会输出你需要的JSON格式:

{
  "a": 1,
  "b": 2,
  "c": 3
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 21:35:25