如何在 C# 中传递带变量的 Json 字符串?

How to pass Json string with variable in c#?

string a;

string b;

string jSonContent = @"{""fields"":{""summary"":""summary"" , ""description"": ""modified.""}}";

我想要 a 而不是 summaryb 而不是 修改。如果我替换摘要,它会工作,但如果我同时替换两者,它会出错。

编辑后的代码是,string jSonContent = @"{""fields"":{""summary"":"+ "\""+ a+ "\"" +" , ""description"": "+ "\""+ b+ "\"" +"}}"; 它没有给出任何错误,摘要字段正在更新,但描述字段不是。

请回复。谢谢!

您可以使用string.Format或string.concate方法

string jSonContent = string.Concat("{\"fields\":{\"summary\":","\"",a,"\" , \"description\": \"",b,"\"}}");

我强烈建议您使用 JSON 库,例如 Json.Net

首先,您将能够使用强类型对象,此外,您将避免拼写错误和类似错误,因为序列化程序会为您进行序列化。

public void Test()
{
    string a = ""; //content of 'a' variable
    string b = ""; //content of 'b' variable

    var obj = new RootObject();
    obj.Fields = new Fields();

    obj.Fields.Summary = a;
    obj.Fields.Description = b;

    var jsonOutput = Newtonsoft.Json.JsonSerializer.Serialize(obj, typeof(RootObject));
}

public class Fields
{
    [JsonProperty("summary")]
    public string Summary { get; set; }

    [JsonProperty("description")]
    public string Description { get; set; }
}

public class RootObject
{
    [JsonProperty("fields")]
    public Fields Fields { get; set; }
}

注意:如果不想创建不必要的类型,可以直接使用JObject,这是一种可能的用法:

var jobj = Newtonsoft.Json.Linq.JObject.FromObject(new {
    fields = new {
        summary = a,
        description = b
    }
});
var jsonOutput = jobj.ToString();
string a = "a";
string b = "b";

string jSonContent = (@"{""fields"":{""summary"":""summary"" , ""description"": ""modified.""}}").Replace(@":""summary""", a).Replace("modified.", b);

使用来自于 $""

的字符串

字符串格式允许您将变量中的值替换为字符串。例如

string name = "Bruno";
string result = $"My name is {name}";
Console.WriteLine(result);

输出将是

My name is Bruno

在你的情况下,你只需要用双括号 {{

来转义 json 括号
string a = "this is a sumary";
string b = "this is a description";
string jSonContent = $"{{\"fields\":{{\"summary\":\"{a}\" , \"description\": \"{b}\"}}}}";

Console.WriteLine(jSonContent);

输出是

{"fields":{"summary":"this is a sumary" , "description": "this is a description"}}

但是我强烈建议不要手动构建 json 字符串,使用 Json.NET 或任何其他 NuGet 包。