首页 > 解决方案 > c#在JSON数据字符串中包含一个变量

问题描述

我正在尝试将 c# 变量传递到以下字符串中,但我真的迷失了如何去做。

这是不使用变量的字符串:

string data = @"{ ""fields"": { 
    ""project"":
    {
        ""key"": ""TEST""
    },
    ""summary"": ""Test Ticket"",
    ""description"": ""test"",
    ""issuetype"": {""name"": ""test""},
    ""assignee"": { ""name"": ""test""}
}}";

然后,当我尝试包含一个变量(test.Text 是一个 asp 文本框)时,我这样做:

string data = @"{ ""fields"": { 
    ""project"":
    {
        ""key"": ""TEST""
    },
    ""summary"": ""Test Ticket"",
    ""description"": """ + test.Text + """,
    ""issuetype"": {""name"": ""test""},
    ""assignee"": { ""name"": ""test"" }
}}";

但这行不通。有没有其他方法可以在其中包含可变数据?

当我尝试构建它时,它会说

} 预期的。

所以我通过并尝试}像这样将每个包裹起来,但它没有帮助:(

string data = @"{ ""fields"": { 
    ""project"":
    {
        ""key"": ""TEST""
    },
    ""summary"": ""Test Ticket"",
    ""description"": {""" + test.Text + """},
    ""issuetype"": {""name"": ""test""},
    ""assignee"": { ""name"": ""test"" }
}}";

谢谢!

标签: c#jsonstringvariables

解决方案


如果您尝试制作 JSON 对象。您最好创建一个作为 JSON 对象蓝图的类。然后使用 NewtonSoft 转换为 JSON 字符串。


namespace example
{
    public class Ticket
    {
        public int Id { get; set; }
        public string Description { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Ticket tic = new Ticket()
            {
                Id = 123,
                Description = "hello motto"
            };

            Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(tic));
            Console.ReadLine();
        }
    }
}

产生结果

{"Id":123,"Description":"hello motto"}

另请注意,您可以将类放在 classe 中,它将正确嵌套。


推荐阅读