c# - 格式化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);
解决方案
您的格式字符串中有大括号,但没有它们是格式项。您可以改用双括号:
// 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);
那样:
- 您无需担心您的姓名、类型等是否包含需要转义的字符
- 您无需担心格式字符串
- 你的代码更容易阅读
推荐阅读
- karate - 空手道工具中的 #ref:java.util.LinkedHashMap 错误
- c - Linux 内核代码似乎忽略了缓存
- node.js - 如何使用 sl api 获取设备访问权限
- nginx - Nginx 和 DigitalOcean 不适用于“www”
- css - CSS 相邻类
- php - gRPC PHP 客户端 HTTP 标头
- biztalk - 在 Disassembler 管道组件中 - 仅从 GetNext() 方法发送最后一条消息
- c# - 数据绑定组合框到文本框
- javascript - ES6 导入和导出语法的“意外令牌 {”错误
- php - Laravel 5.6 - 基于 URL GET 参数登录后重定向到路由