如何让Web Api将Json.net序列化的字符串对象正确地发送回客户端?

Jus*_*mes 6 c# asp.net json.net booksleeve asp.net-web-api

我正在使用JsonConvert.SerializeObject()序列化IEnumerbale对象; 它生成带引号的字符串和带空格的转义字符

从web Api控制器我使用下面的代码返回该字符串

[HttpGet]
public string GetDegreeCodes(int id)
{
    string result = //output from JsonConvert.SerializeObject( );
    return result;
}
Run Code Online (Sandbox Code Playgroud)

"[{\"DegreeId \":1,\"DegreeName \":\"High School \",\"ImageSrc \":\" http://bootsnipp.com/apple-touch-icon-114x114-pre\","描述\":\"获得高中学位\ r \"},{\"DegreeId \":2,\"DegreeName \":\"Associate \",\"ImageSrc \":\" http ://bootsnipp.com/apple-touch-icon-114x114-pre \",\"描述\":\"获得副学士学位\ r \"},{\"DegreeId \":3,\"DegreeName \" :\"Bachelor \","ImageSrc":\" http://bootsnipp.com/apple-touch-icon-114x114-pre \",\"描述\":\"获得学士学位\ r \n" },{\"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]);
            }

        }
    });
Run Code Online (Sandbox Code Playgroud)

我需要使用JsonConvert.SerializeObject,因为我在我的redis缓存服务器中使用booksleeve将其缓存为JSon,这样我每次都不需要重新序列化并从db读取.我如何避免web api控制器发送报价和反斜杠?我可以简单地返回IEnumerable并让Web Api执行JSOn序列化但我需要在redis端缓存它

Kir*_*lla 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;
}
Run Code Online (Sandbox Code Playgroud)

  • 你读过OP的最后一段了吗?用户希望将内容以 Json 形式存储在 Redis 中,因此不想重新序列化该内容。 (2认同)