首页 > 解决方案 > 格式化json字符串并将其传递给带有参数的正文会出错

问题描述

我正在尝试使用 RestSharp 创建一个发布请求。

我有以下字符串

"{ \"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);

标签: c#apirestsharp

解决方案


您的格式字符串中有大括号,但没有它们是格式项。您可以改用双括号:

// 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);

那样:

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

推荐阅读