格式化json String并将其传递给具有参数的主体给出错误

Woj*_*k T 1 c# api restsharp

我正在尝试使用RestSharp创建一个post请求.

我有以下字符串

"{ \"name\": \"string\", \"type\": \"string\", \"parentId\": \"string\", \"Location\": [ \"string\" ]}"
Run Code Online (Sandbox Code Playgroud)

我需要将它传递到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);
}
Run Code Online (Sandbox Code Playgroud)

而错误

Message: System.FormatException : Input string was not in a correct format.
Run Code Online (Sandbox Code Playgroud)

如何格式化上面的字符串以将其传递到json正文?

我的测试在这一行失败了

string NewLocation = string.Format("{ \"name\": \"{0}\", \"type\": \"{1}\", \"parentId\": \"{2}\", \"Location\": [ \"{3}\" ]}", Name, Type, ParentId, Location);
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

您的格式字符串中有开括号,但没有格式项.您可以使用双括号:

// With more properties of course
string newLocation = string.Format("{{ \"name\": \"{0}\" }}", Name);
Run Code Online (Sandbox Code Playgroud)

......但我强烈建议你不要.相反,使用JSON库生成JSON,例如Json.NET.它非常简单,无论是使用类还是匿名类型.例如:

object tmp = new
{
    name = Name,
    type = Type,
    parentId = ParentId,
    Location = Location
};
string json = JsonConvert.SerializeObject(tmp);
Run Code Online (Sandbox Code Playgroud)

那样:

  • 您无需担心您的姓名,类型等是否包含需要转义的字符
  • 您不必担心格式字符串
  • 您的代码更容易阅读

  • (修正了错字.) (2认同)