简体   繁体   English

格式化json字符串并将其传递给带有参数的主体会产生错误

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

I am trying to create a post request using RestSharp. 我正在尝试使用RestSharp创建发布请求。

I have the following string 我有以下字符串

"{ \"name\": \"string\", \"type\": \"string\", \"parentId\": \"string\", \"Location\": [ \"string\" ]}"

I need to pass that into the json body to send a POST request I am trying the following. 我需要将其传递到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);
}

And the error 和错误

Message: System.FormatException : Input string was not in a correct format.

How can I format the above string to pass it into the json body? 如何格式化以上字符串以将其传递到json主体中?

My Test fails at this line 我的测试在这一行失败

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

You've got open braces in your format string, but without them being format items. 您的格式字符串中有大括号,但没有作为格式项。 You could use double braces instead: 可以改用双括号:

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

... but I'd strongly recommend that you don't. ...但是我强烈建议您不要。 Instead, produce JSON using a JSON library, eg Json.NET. 而是使用JSON库(例如Json.NET)生成JSON。 It's really simple, either using classes or anonymous types. 使用类或匿名类型都非常简单。 For example: 例如:

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

That way: 那样:

  • You don't need to worry about whether your name, type etc contain characters that need to be escaped 您无需担心您的姓名,类型等是否包含需要转义的字符
  • You don't need to worry about format strings 您无需担心格式字符串
  • Your code is much easier to read 您的代码更容易阅读

The problem is the curly braces used at the start and end of your format string (since they have a special meaning). 问题是格式字符串的开头和结尾使用花括号(因为它们有特殊含义)。 Escape them by adding an additional brace like so: 通过添加额外的括号来逃避它们,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM