我在使用HttpResponseMessage获取多个Json对象时遇到问题 如果不将字符串包装为Json,怎么能实现呢?
这是我到目前为止尝试过的代码......
private HttpResponseMessage SetToJson(string jsonString)
{
string str = "ABC";
HttpRequestMessage Request = new HttpRequestMessage();
Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration());
Request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
return Request.CreateResponse(HttpStatusCode.OK, new { jsonString, str }, JsonMediaTypeFormatter.DefaultMediaType);
}
它工作正常,但它自己附加“\ n \ r”。如何修复或任何其他替代?
这是上面代码返回的响应
{"jsonString":["{\r\n \"resourceType\": \"Patient\",\r\n \"entry\": []\r\n}","ABC"]}
答案 0 :(得分:2)
好像你把对象序列化了两次。
如果目的是返回正确的对象,那么在创建匿名对象结果之前需要将传入的jsonString
反序列化回一个对象,最终会在http meddage响应中再次序列化回json
private HttpResponseMessage SetToJson(string jsonString) {
string str = "ABC";
var Request = new HttpRequestMessage();
Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration());
Request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
var obj = JsonConvert.DeserializeObject(jsonString);
return Request.CreateResponse(HttpStatusCode.OK, new { obj, str }, JsonMediaTypeFormatter.DefaultMediaType);
}