Tell modelbinding that MVC action parameter is JSON - json

I am using an upload control to send a file to a JsonResult, but I am also sending up a JSON string as a second parameter. This is all getting posted with the Content-Type:multipart/form-data;
[HttpPost]
public JsonResult UploadDocument(HttpPostedFileBase file, DocumentViewModel model)
{ ... }
I know MVC is capable of binding directly to a viewmodel if the content type is set to application/json but I don't think it's possible for me to set that in this case.
Is there any way for me to get MVC to automatically bind my posted json string to model?

That's not possible out-of-the-box. You will have to manually deserialize the JSON string parameter that you would read from the request to your view model inside the controller action or write a custom model binder for it that will do the job. Ideally you shouldn't be posting the model data as a JSON string but rather respect the content type you specified : multipart/form-data. So the correct way to handle this scenario is to modify the client code that is sending the request in order to respect the content type.

As I was unable to change the content-type I found this blog to be exactly what i needed.
"... our whole request stream(data) won’t be json string. Only the guest parameter will be supplied as json string..."
http://ishwor.cyberbudsonline.com/2012/07/fun-with-aspnet-mvc-3-custom-json-model-binder.html

Related

JAX-RS JSON Binding deserialization error when using multiple parameter in POST

I'm trying to develop a Jax-RS POST resource, reported here below:
#Path("testJson")
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response testJson(Float firstValue, Float secondValue, String thirdValue) {
LOG.info(" firstValue: " + firstValue);
LOG.info(" secondValue: " + secondValue);
LOG.info(" thirdValue: " + thirdValue);
return Response.ok().build();
}
However, i get the following error:
RESTEASY002305: Failed executing POST /aliments/testJson: org.jboss.resteasy.spi.ReaderException: javax.ws.rs.ProcessingException: RESTEASY008200: JSON Binding deserialization error
Searching around, I understood that for a POST method that accepts a JSON, you need to give to it only one parameter, which is in fact the entire JSON message.
My questions are:
Why can't I put two or more parameters? Is that because the Json represents the body part of the message and I can have only one body? Can you explain it better to me please?
I can create a DTO that contains my parameters and use this DTO as one and only parameter for my POST method, but is this the best practice? Doing so, I will have a DTO for each POST method, which actually acts as a Wrapper.
Is there anything I'm missing?
Thank you a lot for your time,
Have a nice day.
Why can't I put two or more parameters? Is that because the Json represents the body part of the message and I can have only one body? Can you explain it better to me please?
JAX-RS allows for one "entity" parameter. This parameter represents the entire request entity. It is determined to be the entity parameter by not having any annotations1. If you want the raw entity, you can use an InputStream parameter. If you want a POJO, you can do so. How the conversion works is with the use of MessageBodyReaders. The reader will be chosen based on the Content-Type header and the parameter type. The framwork comes with some standard readers for easiliy convertable types. For example String, InputStream, byte[]. The reader will get passed the entity stream and it will need to convert the stream to the parameter type. You can read more about "Entity Providers" here.
If you want to use a common media type like JSON, there are libraries that handle JSON/POJO conversion, and from that library, a reader can be made. For JSON, a common librabry is Jackson, and there is a Jackson MessageBodyReader that is provided by the Jackson team.
I can create a DTO that contains my parameters and use this DTO as one and only parameter for my POST method, but is this the best practice? Doing so, I will have a DTO for each POST method, which actually acts as a Wrapper.
Yes, this is very common practice. Get used to it with these type of frameworks.
Is there anything I'm missing?
I don't know, you tell me.
1. Some special annotation are allowed like #Valid for bean validation.

Return JSON Result from an Api Controller

I'm building an Api Controller and I need to serialize my List to JSON as my action result.but It seems that such statements doesn't work
return Json(data, JsonRequestBehavior.AllowGet);
How can I achieve this ?
As you mentioned that you are using WEB API, I'm assuming it has the JsonFormatter configured. With that said, the responsibility to convert you action result into a JSON is not of your action but from the Media Type Formatter chosen as part of the Content Negotiation process.
That said, it's enough for your Action to return the actual List type and the Web API Media Type formatter will take care of formatting it to JSON.
For example, let's say that data is a List<Foo> where Foo is some type that you created. It is enough for your controller action to be:
public List<Foo> GetFoo()
{
var data = GetListOfFoo();
return data;
}
Have you tried using a JSON serializtion class?
I have had success using the ideas put forward in this article:
Serializing a list to JSON
Or, if you don't want to use serialization, the example for an action result using JSON in MSDN just uses a generic list object.

Pass JSON object vs JSON string in HTTP POST

I'm building a REST API in JAVA and C# and I was wondering about the way I should pass data to those services.
What I'm familiar with as the right way is to send JSON object as the data in the POST body:
{name:'Dor'}
but I can also pass a string and parse the JSON in my service:
'{name:'Dor'}'
What is the preferable way from performance factor? or any other factors?
Basically, if you need to send the json data across via jquery, then we need to use stringify, else the data would be serialized into to key=value pair.
So, you cannot send the json object directly via jquery ajax method.
How it works behind the hood:
In $.ajax function, if we provide data as
data :{key1:"value1", key2:"value2"}
is serialized to key1=value1&key2=value2
if we provide data as
data :'{key1:"value1", key2:"value2"}' or JSON.stringify({key1:"value1", key2:"value2"})
is sent as {key1:"value1", key2:"value2"}
So, what we can conclude is that, we cannot pass json object directly via jquery, we can send only json string. Hope this clarifies everyone.

Spring RESTful service returning JSON from another service

I have been creating Spring RESTful services for a while and typically I am building my own services so I create domain objects and populate them and the framework takes care of the conversion to JSON.
I have a situation now where I simply need my service to act as a pass through to another system's service that is already RESTful and returns JSON.
URL https://:/service/serviceInfo
Method GET
HTTP Content Type Produces: application/json
I simply want to wrap this call (I will apply some security checks on the service) and pass that JSON returned straight back to my service without mapping it back to Java objects, only to return as JSON to the client. Is there a simple way to do this, with minimal code?
Thanks in advance.
Can you see if this works for you?
#RequestMapping("/child")
public String testMethod(#RequestParam String param) {
return new RestTemplate().exchange("https://api.twitter.com/1/statuses/user_timeline.json", HttpMethod.GET, null, String.class).getBody();
}
You just replace the url for your own. I can also guide you to using the RestTemplate with POST or DELETE requests etc. if you need. Also adding parameters or headers if you need. I've used it extensively in some projects.

Setting a JSON Object from an input field

I basically have the following flow:
XML -> JSON -> Spring MVC -> jsp page, which is displayed as a table with editable fields.
How do make is so that when i edit a field value it correct updates the Json Object?
I have used some nasty hacking at the moment, as i know (testing) the values/object I am going to get, so im just parsing the JSON string in javascript and sending that back.
So i can then just convert the json object (with new values) and post it back.
Cheers.
You could use the serialize method from prototypejs.
http://www.prototypejs.org/api/form/serialize
just by calling .serialize() you'll be able to get the updated object.