我正在尝试使用RestSharp创建一个post请求。
我有以下字符串
"{ "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);
}
和错误
Message: System.FormatException : Input string was not in a correct format.
如何格式化上述字符串以将其传递到 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);
那边:
- 您无需担心您的姓名、类型等是否包含需要转义的字符
- 您无需担心格式字符串
- 您的代码更易于阅读
问题是格式字符串开头和结尾使用的花括号(因为它们具有特殊含义)。通过添加额外的大括号来转义它们,如下所示:
string NewLocation = string.Format("{{ "name": "{0}", "type": "{1}", "parentId": "{2}", "Location": [ "{3}" ]}}", Name, Type, ParentId, Location);