How to return a Json object from a C # method

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\"]}"; // TEST !!!!! var response = Request.CreateResponse(HttpStatusCode.OK); response.Content = new StringContent(resp, System.Text.Encoding.UTF8, "application/json"); return response; } 

in the Chrome console, the answer is:

 Object {status: "SUCCESS", data: Array[1]} data: Array[1] status: "SUCCESS" __proto__: Object 
+13
source share
3 answers

resp already a JSON string, but JSON is invalid (keys are not enclosed in quotation marks ( " ). If it is returned in angular, the JavaScript JSON.parse () method could not deserialize it. However, you can use JSON.NET to deserialize it into JObject and serialize it again into valid JSON and create your own HttpResponseMessage ...

 public HttpResponseMessage Get() { string userid = UrlUtil.getParam(this, "userid", ""); string pwd = UrlUtil.getParam(this, "pwd", "" ); string resp = DynAggrClientAPI.openSession(userid, pwd); var jObject = JObject.Parse(resp); var response = Request.CreateResponse(HttpStatusCode.OK); response.Content = new StringContent(jObject.ToString(), Encoding.UTF8, "application/json"); return response; } 

Or you can just return the JObject and have a web interface for serializing it for you ...

 public JObject Get() { string userid = UrlUtil.getParam(this, "userid", ""); string pwd = UrlUtil.getParam(this, "pwd", "" ); string resp = DynAggrClientAPI.openSession(userid, pwd); var jObject = JObject.Parse(resp); return jObject; } 

In any case, the Web API call should return this JSON, which is now valid ...

 { "status": "SUCCESS", "data": [ "4eb97d2c6729df98206cf214874ac1757649839fe4e24c51d21d" ] } 

In angular code, you have to dig out the session identifier, which is stored in an array called data ...

 userService.openUserSession(rzEnvJson).then(function (response) { var sessionResponse = response.data; // or simply response, depending if this is a promise returned from $http $rootScope.rgSessionVars.sessionID = sessionResponse.data[0]; }); 
+28
source

I do not see how this is related to AngularJS, but your problem is simple. Your data object is JSON encoded. That way you will almost certainly be able to access data.JsonRequestBehavior , and that will be 1 . But the data field inside it is AGAIN JSON-encoded. You must decode it before trying to use it - it's just a line when you get to this callback:

 var myData = angular.fromJson(data.Data); console.log(myData.data); 

Note that your data.Data object itself is another wrapper - an array. You almost certainly want myData.data[0] go into this sessionID field ...

+2
source

The key to what's happening here is in a comment made by Mike Chill ; serialization occurs twice, once in OP code and once in Asp.Net WebAPI . That's why instead of a Json object, a Json returned.

I came across the same thing. Here is an example Hello world showing a problem. At first I did something like this:

 [Route("getall")] public string GetAllItems() { var result = new { x = "hello", y = "world" }; return JsonConvert.SerializeObject(result); } 

Then I tried to do something like this, thinking that I need to return IHttpActionResult in order to solve this problem:

 [Route("getall")] public IHttpActionResult GetAllItems() { var result = new { x = "hello", y = "world" }; return Ok(JsonConvert.SerializeObject(result)); } 

Both of these controller actions gave me the string, and not the Json object I wanted; here I am:

 "{\"x\":\"hello\",\"y\":\"world\"}" 

Finally, I saw Mike's comment and realized that I needed to return the .Net object directly and just let WebAPI handle serialization. Therefore, instead of returning this:

 return Ok(JsonConvert.SerializeObject(result)); 

return this:

 return Ok(result); 

Then I got the expected result:

 {"x":"hello","y":"world"} 
+1
source

Source: https://habr.com/ru/post/973382/


All Articles