c# - 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"" }
}}";
谢谢!
解决方案
如果您尝试制作 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 中,它将正确嵌套。
推荐阅读
- amazon-web-services - 如何减少 AWS Windows EBS 根卷?
- git - Git错误:git credential-manager-core的waitpid失败:没有子进程
- vb.net - 使用 Visual Basic 从我的桌面删除图像
- azure-devops-server - 是否可以使用 OAuth 令牌克隆 Azure Devops 存储库
- css - 为多个登陆页面优化 CSS
- python - 嵌套for循环有更好的选择吗?
- c# - 如何以编程方式控制由无限递归方法调用或无限循环引起的 StackOverflow 异常?
- android - 在android studio中无法初始化编辑器错误
- javascript - 如何连接两个对象并替换值?
- java - 我们如何在 Serenity BDD API 测试中同时使用“request.headers”和“requestpathParam”?