如何在C#中将字符串变量转换为json格式

How to convert string Variable to json format in C#

我有一种情况需要将 4 个字符串变量转换并合并为一个 json 格式字符串。下面是我正在尝试做的例子。

我的 4 个变量:

string SQLServerType = "SQLVM";
string ServerName = "ABCDEF";
string DatabaseName = "WhatEver";
string TriggerStatus = "Disabled";

如何将以上 4 个变量的值合并为以下 json 格式?

{
   "SQLServerType":"SQLVM",
   "ServerName":"ABCDEF",
   "DatabaseName":"WhatEver",
   "TriggerStatus":"Disabled"
}

试试这个

var json  = JsonConvert.SerializeObject( new Dictionary<string,string> {
        { nameof(SQLServerType), SQLServerType},
        { nameof(ServerName), ServerName},
        { nameof(DatabaseName), DatabaseName},
        { nameof(TriggerStatus), TriggerStatus}
    });

结果

{"SQLServerType":"SQLVM","ServerName":"ABCDEF","DatabaseName":"WhatEver","TriggerStatus":"Disabled"}

感谢@Nick Bailey 提供 link。 我从@Nick Bailey How to write .NET objects as JSON (serialize)

的评论中找到了答案
string SQLServerType = "SQLVM";
string ServerName = "ABCDEF";
string DatabaseName = "WhatEver";
string TriggerStatus = "Disabled";

string CombinedJsonValue = "";

var JsonSQLTriggers = new SQLTriggers
{
    SQLServerType = SQLServerType,
    ServerName = ServerName,
    DatabaseName = DatabaseName,
    TriggerStatus = TriggerStatus
};

string jsonString = System.Text.Json.JsonSerializer.Serialize(JsonSQLTriggers);