我使用JsonConvert.SerializeObject()序列化IEnumerbale对象; 它生成带引号的字符串和带空格的转义字符
来自web Api控制器的我使用下面的代码
返回该字符串[HttpGet]
public string GetDegreeCodes(int id)
{
string result = //output from JsonConvert.SerializeObject( );
return result;
}
“[{\”DegreeId \“:1,\”DegreeName \“:\”High School \“,\”ImageSrc \“:\” http://bootsnipp.com/apple-touch-icon-114x114-pre \ “\ ”描述\“:\” 上高中 度\ r \ “},{\” DegreeId \ “:2,\” DegreeName \ “:\” 联系\ “\ ”ImageSrc \“:\” http://bootsnipp.com/apple-touch-icon-114x114-pre \ “\ ”描述\“:\” 获得助理 度\ r \ “},{\” DegreeId \ “:3,\” DegreeName \ “:\” 本科\ “\ ”ImageSrc \“:\” http://bootsnipp.com/apple-touch-icon-114x114-pre \ “\ ”描述\“:\” 获得学士学位 度\ r \ “},{\” DegreeId \ “:4,\” DegreeName \ “:\” 大师\ “\ ”ImageSrc \“:\” http://bootsnipp.com/apple-touch-icon-114x114-pre \ “\ ”描述\“:\” 得到主人 度\ r \ “},{\” DegreeId \ “:5,\” DegreeName \ “:\” Doctrate \ “\ ”ImageSrc \“:\” http://bootsnipp.com/apple-touch-icon-114x114-pre \ “\ ”描述\“:\” 获得博士学位\“}]”
这是我的ajax,由于额外的包装引号和转义字符,它无法正确识别JSON,
$.ajax({
url: "/api/helloservice/getdegreecodes",
type: "get",
contentType: "application/text",
data: { id: 1 }
}).done(function (data) {
if (data.length > 0) {
for (i = 0; i < data.length; i++) {
viewEduModel.degreeCodes.push(data[i]);
}
}
});
我需要使用JsonConvert.SerializeObject,因为我将其缓存为JSon 在我的redis缓存服务器中使用booksleeve这种方式我不需要 每次都重新序列化并从db读取。我该如何避免web api控制器发送 行情和反斜杠?我可以简单地返回IEnumerable和 让Web Api执行JSOn序列化,但我需要将它缓存在redis上 侧
答案 0 :(得分:14)
你可以像下面这样:
[HttpGet]
public HttpResponseMessage GetDegreeCodes(int id)
{
StringContent sc = new StringContent("Your JSON content from Redis here");
sc.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpResponseMessage resp = new HttpResponseMessage();
resp.Content = sc;
return resp;
}
答案 1 :(得分:0)
使用此功能,您可以通过代码调用您的webapi。
using (var client = new WebClient()) //WebClient
{
string mystring = "";
client.Headers.Add("Content-Type:application/json"); //Content-Type
client.Headers.Add("Accept:application/json");
var dataa = Encoding.UTF8.GetBytes("{\"Username\":\"sdfsd\"}");
byte[] a = client.UploadData("your API url", "POST",dataa);
myString = Encoding.UTF8.GetString(a);
}
&#13;