格式化 json 字符串并将其传递给带有参数的正文给出错误

Format json String and pass it to the body with parameters gives error

我正在尝试使用 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);