Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am serializing an IEnumerbale object using JsonConvert.SerializeObject( ); it produces string with quotes and escape character with spaces

from web Api controller i return that string using code below

[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\":\" Get High School Degree\r\"},{\"DegreeId\":2,\"DegreeName\":\"Associate\",\"ImageSrc\":\" http://bootsnipp.com/apple-touch-icon-114x114-pre\",\"Description\":\" Get Associate Degree\r\"},{\"DegreeId\":3,\"DegreeName\":\"Bachelor\",\"ImageSrc\":\" http://bootsnipp.com/apple-touch-icon-114x114-pre\",\"Description\":\" Get Bachelor Degree\r\"},{\"DegreeId\":4,\"DegreeName\":\"Masters\",\"ImageSrc\":\" http://bootsnipp.com/apple-touch-icon-114x114-pre\",\"Description\":\" Get Master Degree\r\"},{\"DegreeId\":5,\"DegreeName\":\"Doctrate\",\"ImageSrc\":\" http://bootsnipp.com/apple-touch-icon-114x114-pre\",\"Description\":\" Get Doctorate Degree\"}]"

This is my ajax and it does not recognize the JSON correctly because of the extra wrapper quotes and escape characters,

$.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]);
            }

        }
    });

i need to use JsonConvert.SerializeObject since i am caching it as a JSon in my redis cache server using booksleeve that way I do not need to re serialize and read from db every time. how do i avoid web api controller sending Quotes and backslashes? i could simply return IEnumerable and let Web Api do the JSOn serialization but i need to cache it on redis side

like image 490
Justin Homes Avatar asked Jan 27 '14 15:01

Justin Homes


1 Answers

You could something like below:

[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;
}
like image 186
Kiran Avatar answered Nov 14 '22 23:11

Kiran