How to make Web Api send Json.net Serialized string object back to the client Correct?

I serialize an IEnumerbale object using JsonConvert.SerializeObject (); it creates a string with quotes and escape character with spaces

from api web controller i am returning this line 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 \ g \ "}, {\" DegreeId \ ": 2, \" DegreeName \ ": \" Associate \ "\" IMAGESRC \ ": \" http: //bootsnipp.com/apple-touch-icon-114x114-pre \ ", \" Description \ ": \" Get the associated Degree \ g \ "}, {\" DegreeId \ ": 3, \" DegreeName \ ": \ "Bachelor \" \ "IMAGESRC \": \ " http://bootsnipp.com/apple-touch-icon-114x114-pre \", \ "Description \": \ "Get a bachelor's degree \ g \"}, {\ "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 a doctorate \ "}]"

This is my ajax and it does not recognize JSON correctly due to extra shell 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 cache it like JSon in my redis cache server using bookleeve, so I don't need to re serialize and read from db every time. How can I avoid sending the web api manager Quotes and backslash? I can just return IEnumerable and let Web Api serialize JSOn, but I need to cache it on the redis side

+6
source share
2 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; } 
+13
source

using this, you can call via webapi through code.

 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); } 
0
source

All Articles