I am trying to fix an ASP.NET WebAPI method where a Json response is required. However, it returns a string instead.
It was originally an XML format, but I added this line to the mvc code in App_Start \ WebApiConfig.cs to return Json by default.
config.Formatters.Remove(config.Formatters.XmlFormatter);
We updated the c # method as follows to use NewtonSoft:
public string Get() { string userid = UrlUtil.getParam(this, "userid", ""); string pwd = UrlUtil.getParam(this, "pwd", ""); string resp = DynAggrClientAPI.openSession(userid, pwd); JsonSerializer ser = new JsonSerializer(); string jsonresp = JsonConvert.SerializeObject(resp); return resp; }
Acc. var is returned as a string type:
"{status:\"SUCCESS\",data:[\"4eb97d2c6729df98206cf214874ac1757649839fe4e24c51d21d\"]}"
and jsonresp var looks like this:
"\"{status:\\\"SUCCESS\\\",data:[\\\"4eb97d2c6729df98206cf214874ac1757649839fe4e24c51d21d\\\"]}\""
and in the Chrome F12 developer tools, the data object:
""{status:\"SUCCESS\",data:[\"4eb97d2c6729df98206cf214874ac1757649839fe4e24c51d21d\"]}""
and in Console Tools, the result of angular.fromJson (data):
"{status:"SUCCESS",data:["4eb97d2c6729df98206cf214874ac1757649839fe4e24c51d21d"]}"
I would like to get some tips on how to properly return a Json object, NOT in any type of string.
UPDATE
By intercepting the resp variable and using Mr. Chu's suggestion below, I can successfully get a nice clean Json object on the client. The key is that resp must contain double quotes around both key: value pairs:
public HttpResponseMessage Get() { string userid = UrlUtil.getParam(this, "userid", ""); string pwd = UrlUtil.getParam(this, "pwd", ""); string resp = DynAggrClientAPI.openSession(userid, pwd); resp = "{\"status\":\"SUCCESS\",\"data\":[\"194f66366a6dee8738428bf1d730691a9babb77920ec9dfa06cf\"]}";
in the Chrome console, the answer is:
Object {status: "SUCCESS", data: Array[1]} data: Array[1] status: "SUCCESS" __proto__: Object