C# 格式化json字符串,并将其传递给带有参数的正文,这会导致错误
我正在尝试使用RestSharp创建post请求 我有以下字符串C# 格式化json字符串,并将其传递给带有参数的正文,这会导致错误,c#,api,restsharp,C#,Api,Restsharp,我正在尝试使用RestSharp创建post请求 我有以下字符串 "{ \"name\": \"string\", \"type\": \"string\", \"parentId\": \"string\", \"Location\": [ \"string\" ]}" 我需要将其传递到json主体以发送POST请求,我正在尝试以下操作 public IRestResponse PostNewLocation(string Name, string Type, Nullable<Gui
"{ \"name\": \"string\", \"type\": \"string\", \"parentId\": \"string\", \"Location\": [ \"string\" ]}"
我需要将其传递到json主体以发送POST请求,我正在尝试以下操作
public IRestResponse PostNewLocation(string Name, string Type, Nullable<Guid> ParentId, string Locatations)
{
string NewLocation = string.Format("{ \"name\": \"{0}\", \"type\": \"{1}\", \"parentId\": \"{2}\", \"Location\": [ \"{3}\" ]}", Name, Type, ParentId, Location);
var request = new RestRequest(Method.POST);
request.Resource = string.Format("/Sample/Url");
request.AddParameter("application/json", NewLocation, ParameterType.RequestBody);
IRestResponse response = Client.Execute(request);
}
如何格式化上述字符串以将其传递到json正文中
我的测试在这一行失败了
string NewLocation = string.Format("{ \"name\": \"{0}\", \"type\": \"{1}\", \"parentId\": \"{2}\", \"Location\": [ \"{3}\" ]}", Name, Type, ParentId, Location);
格式字符串中有打开的大括号,但它们不是格式项。您可以改为使用双大括号:
// With more properties of course
string newLocation = string.Format("{{ \"name\": \"{0}\" }}", Name);
。。。但我强烈建议你不要这样做。相反,使用JSON库生成JSON,例如JSON.NET。它非常简单,可以使用类,也可以使用匿名类型。例如:
object tmp = new
{
name = Name,
type = Type,
parentId = ParentId,
Location = Location
};
string json = JsonConvert.SerializeObject(tmp);
这样:
- 您不必担心您的姓名、类型等是否包含需要转义的字符
- 您不必担心格式字符串
- 你的代码更容易阅读
// With more properties of course
string newLocation = string.Format("{{ \"name\": \"{0}\" }}", Name);
。。。但我强烈建议你不要这样做。相反,使用JSON库生成JSON,例如JSON.NET。它非常简单,可以使用类,也可以使用匿名类型。例如:
object tmp = new
{
name = Name,
type = Type,
parentId = ParentId,
Location = Location
};
string json = JsonConvert.SerializeObject(tmp);
这样:
- 您不必担心您的姓名、类型等是否包含需要转义的字符
- 您不必担心格式字符串
- 你的代码更容易阅读
- 问题在于格式字符串的开头和结尾使用了大括号(因为它们有特殊的含义)。通过添加一个附加的大括号将其转义,如下所示:
string NewLocation = string.Format("{{ \"name\": \"{0}\", \"type\": \"{1}\", \"parentId\": \"{2}\", \"Location\": [ \"{3}\" ]}}", Name, Type, ParentId, Location);
问题在于格式字符串的开头和结尾使用了大括号(因为它们有特殊的含义)。通过添加一个附加的大括号将其转义,如下所示:
string NewLocation = string.Format("{{ \"name\": \"{0}\", \"type\": \"{1}\", \"parentId\": \"{2}\", \"Location\": [ \"{3}\" ]}}", Name, Type, ParentId, Location);
啊,是的,谢谢你的另一个例子,我会尝试:)仅供参考,你在
名称
”中有一个输入错误(纠正了输入错误。)啊,是的,谢谢你的另一个例子,我会尝试:)仅供参考,你在名称
”中有一个输入错误(纠正了输入错误。)