I have ApiController which receives a specific object of a class. That works perfect but what if, HTTP Request which contains a body with JSON is not matching with the object of a class? I will receive a null value of object because there is not a match between JSON and object of a class. My question is, how to get original JSON request when a user sends JSON with an incorrect format?
public class Document{
string name;
int number;
}
JSON REQUEST
{
"name":"Default name",
"number":91526861713"
}
JSON IS INCORRECT BECAUSE DATA TYPE OF number is int, not string "234" !
Automatically documentObject in function is equal to null.
How to get original JSON REQUEST?
[HttpPost]
public IHttpActionResult Receiving([FromBody]Document documentObject)
{
}
you can use Request.Content , But output is raw string.
like this:
[HttpPost]
public async Task<IHttpActionResult> Receiving([FromBody]Document documentObject)
{
var content = await Request.Content.ReadAsStringAsync();
return Json(content); // output => "name=xxx&number=123"
}
Here is my code:
[HttpGet]
[Produces("application/json")]
[Route("whatever")]
public ActionResult<JsonResult> Get()
{
string jsonText = "{\"city\":\"paris\"}";
return new JsonResult(JObject.Parse(jsonText));
}
This is the output I want:
{"city":"paris"}
This is the output I get:
{"contentType":null,"serializerSettings":null,"statusCode":null,"value":{"city":"paris"}}
How can I change my code to prevent .NET framework from wrapping my original JSON?
Then use a simpler and strongly typed result object instead of trying to manually create the JSON string.
[HttpGet]
[Produces("application/json")]
[Route("whatever")]
public IActionResult Get() {
var model = new { city = "paris" };
return Ok(model);
}
the framework will serialize the model to the desired output
There is no problem with ASP.NET MVC's JsonResult, but you're using JSON.NET. In JSON.NET, when you convert an json string vi JObject.Parse(), it returns a JObject object that contains some members. If you want to get the converted json, you should use ToString(), as the following:
[HttpGet]
[Produces("application/json")]
[Route("whatever")]
public ActionResult<JsonResult> Get()
{
string jsonText = "{\"city\":\"paris\"}";
return new JsonResult(JObject.Parse(jsonText).ToString());
}
I have a method that originally returned an HttpResponseMessage and I'd like to convert this to return IHttpActionResult.
My problem is the current code is using JSON.Net to serialize a complex generic tree structure, which it does well using a custom JsonConverter I wrote (the code is working fine).
Here's what it returns:
string json = NodeToJson(personNode);
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(json, Encoding.UTF8, "application/json");
return response;
The NodeToJson method is where the custom converter comes into play ...
private static string NodeToJson(Node<Person> personNode) {
var settings = new JsonSerializerSettings {
Converters = new List<JsonConverter> { new OrgChartConverter() },
Formatting = Formatting.Indented
};
return JsonConvert.SerializeObject(personNode, settings);
}
Note this returns a string, formatted as JSON.
If I switch this to IHttpActionResult, it seems to fail regardless of what I try. I can just leave it (it works) but I am supposed to be using best practices for this and IHttpActionResult seems to be what I should be using.
I have tried to return Json(json); but this results in invalid, unparsable JSON, presumably because it's trying to do a double conversion?
return Ok(json); results in the JSON string being wrapped in XML.
What is the right way to do this?
EDIT:
I have successfully converted every method in this project to use IHttpActionResult now except this particular method.
It's a serialization of a generic tree to JSON. Regardless of what approach I try, I get back invalid JSON. The HttpResponseMsessage approach works fine, but I can not get valid JSON back with IHttpActionResult.
You can create your own IHttpActionResult class instance to return the JSON and a method in your controller or base controller class to utilize it.
Create the IHttpActionResult instance that sets the content and status code:
public class JsonTextActionResult : IHttpActionResult
{
public HttpRequestMessage Request { get; }
public string JsonText { get; }
public JsonTextActionResult(HttpRequestMessage request, string jsonText)
{
Request = request;
JsonText = jsonText;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
return Task.FromResult(Execute());
}
public HttpResponseMessage Execute()
{
var response = this.Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(JsonText, Encoding.UTF8, "application/json");
return response;
}
}
Add a method to your controller to create the result. Here is a Web API example:
public class MyApiController : ApiController
{
protected internal virtual JsonTextActionResult JsonText(string jsonText)
{
return new JsonTextActionResult(Request, jsonText);
}
[HttpGet]
public IHttpActionResult GetJson()
{
string json = GetSomeJsonText();
return JsonText(json);
}
}
Another recommendation is as below;
var json = JToken.FromObject(yourObject);
return Ok(json);
I've got the same problem and this piece of code worked for me (Using Newtonsoft.Json nuget package to deserialize the json):
var unserializedContent = JsonConvert.DeserializeObject(json);
return Json(unserializedContent);
It seems we must have an object in order to Json() work as it should.
Some of the solutions here are converting string to JSON, that's not necessary.
You are just using computer resources for nothing.
// Instead of
// return Ok(jsonstring);
// do:
HttpResponseMessage response = this.Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(jsonstring, Encoding.UTF8, "application/json");
Request.RegisterForDispose(response); //To avoid the Pragma CA2000 warning
return ResponseMessage(response);
Another solution At client side
You can make a small change to be prepared to receive a string and convert it if necessary. The code bellow is Javascript
var data;
if (typeof weapiresponse == "string")
data = JSON.parse(weapiresponse);
else
data = weapiresponse;
If you have no intention of using XML as a return type, you can also remove the XmlFormatter in your WebApiConfig:
config.Formatters.Remove(config.Formatters.XmlFormatter);
The correct way is to return:
Ok(json);
It's converting the result to XML because that's the default accepted return type. Try adding:
Accept: application/json into your API request headers, I think that should resolve the issue.
I had the same problem with web-service returning JSON string in a XML-tag. I tried all the simple solutions Like :
return Json(text) , json deserialize and adding config.Formatter for json, but that did't help. I got double cotes around the json object or it was malformed.
Only the solution written by TGRA worked for me.
create your own IHttpActionResult class instance to return the JSON
For me, the only way to return an IHttpActionResult with the string content as Json in the following.
[HttpGet]
public IHttpActionResult ReturnStringAsJson()
{
return this.ResponseMessage(new HttpResponseMessage
{
Content = new StringContent("[json string]"),
Encoding.UTF8,
"application/json"),
});
}
I have an object which I return wrapped in Json from the controller to the client.
return Json(result); //result is DataSourceResult
I would like to add some more properties inside this Json response.
How can I do so?
I tried using Json property Data and also casting the DataSourceResult to object and trying to expand it, but whatever I have doesn't look like a good solution.
You can return anonymous object like
return Json(new {
result = result,
myProperty1 = value1,
myProperty2 = value2
});
I have a function that send a JSONResult, Now i want to use that function in C# and convert that JSONResult to IEnumerable so i can iterate on that result and pass that data to a SelectList function. Can i do this and how? Im using Asp.Net MVC, JQuery and C#
why not:
public myObject GetMyObject()
{
myRepository db = new myRepository();
return db.ListAllStuff();
}
public JsonResult GetMyJSON()
{
return Json(GetMyObject(), JsonRequestBehavior.AllowGet);
}
public List<SelectList> GetMyEnumerable()
{
return this.GetMyObject().ToList();
}
and you are reusing everything.
Also it can be done in this way.
var data = GetJsonResultData(); //call to JsonResult method.
var datastr = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(data.Data); // convert json object to string.
var dataclass = Newtonsoft.Json.JsonConvert.DeserializeObject<List<modeldto>>(datastr ); // string json data to class list