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

如何将C#格式的JSON字符串转换为标准JSON字符串?

解决C#手动拼接JSON转标准JSON字符串的问题

嘿,我太懂手动拼接JSON字符串的糟心了——不仅容易漏个逗号、错个引号,后期改起来也头疼!别再硬拼了,用序列化工具才是靠谱的做法,给你几种简单好用的方案:

方法1:匿名对象 + JSON序列化(最推荐)

不管你用的是.NET Core/.NET 5+自带的System.Text.Json,还是老牌的Newtonsoft.Json(Json.NET),都能轻松把C#对象转成标准JSON,完全不用手动拼字符串。

用System.Text.Json(.NET Core/.NET 5+内置,无需额外安装包)

using System.Text.Json;

// 先定义一个匿名对象,结构和你要的JSON对应
var authPayload = new 
{
    grant_type = "password",
    client_id = 2,
    client_secret = "ClientSecretHere",
    username = "abc@company.com",
    password = "somepassword"
};

// 直接序列化得到标准JSON
string standardJson = JsonSerializer.Serialize(authPayload);
// 输出结果就是你要的:{"grant_type":"password","client_id":2,...}

用Newtonsoft.Json(适合.NET Framework或习惯用Json.NET的场景)

如果你的项目是.NET Framework,或者已经引用了Json.NET,就用这个:

using Newtonsoft.Json;

var authPayload = new 
{
    grant_type = "password",
    client_id = 2,
    client_secret = "ClientSecretHere",
    username = "abc@company.com",
    password = "somepassword"
};

string standardJson = JsonConvert.SerializeObject(authPayload);

方法2:动态构建JObject(Newtonsoft.Json)

如果需要动态添加属性,或者不想用匿名对象,直接用JObject来构造也很方便:

using Newtonsoft.Json.Linq;

var jsonObj = new JObject
{
    ["grant_type"] = "password",
    ["client_id"] = 2,
    ["client_secret"] = "ClientSecretHere",
    ["username"] = "abc@company.com",
    ["password"] = "somepassword"
};

string standardJson = jsonObj.ToString();

为啥别再手动拼接?

  • 太容易出错:比如漏逗号、引号不匹配,尤其是字符串里有特殊字符(比如双引号、反斜杠)时,手动转义简直噩梦,序列化工具会自动处理这些细节
  • 代码难维护:后期要加个属性或者改个值,硬拼的字符串要找半天,用对象的话直接改属性就行
  • 可读性差:硬拼的字符串一眼看不清楚结构,用对象一目了然

用上面的方法生成的JSON绝对是标准格式的,完全满足你的需求!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:45:02