6

我正在使用 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 \ ",\"Description\":\" 获取高中学位\r\"},{\"DegreeId\":2,\"DegreeName\":\"Associate\",\"ImageSrc\":\" http ://bootsnipp.com/apple-touch-icon-114x114-pre \",\"Description\":\" 获得副学士学位\r\"},{\"DegreeId\":3,\"DegreeName\" :\"Bachelor\",\"ImageSrc\":\" http://bootsnipp.com/apple-touch-icon-114x114-pre \",\"Description\":\" 获得学士学位\r\" },{\"DegreeId\":4,\"DegreeName\":\"Masters\", \"ImageSrc\":\" http://bootsnipp.com/apple-touch-icon-114x114-pre \",\"Description\":\" 获取硕士学位\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,因为我使用 bookleeve 将它作为 JSon 缓存在我的 redis 缓存服务器中,这样我就不需要每次都重新序列化并从 db 读取。如何避免 Web api 控制器发送引号和反斜杠?我可以简单地返回 IEnumerable 并让 Web Api 进行 JSOn 序列化,但我需要将它缓存在 redis 端

4

2 回答 2

15

你可以像下面这样:

[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;
}
于 2014-01-27T15:46:49.047 回答
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);
  
  }

于 2016-12-29T11:16:53.453 回答