繁体   English   中英

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

[英]how to have Web Api send Json.net Serialized string object back to client Correctly?

我正在使用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 \\“:\\”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]);
            }

        }
    });

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

你可以像下面这样:

[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;
}

通过使用它,您可以通过代码调用您的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); } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM