Post JSON To Spring REST Webservice - Level Up Lunch
Post JSON To Spring REST Webservice - Level Up Lunch
M≡NU
Java / Tutorials
On this page +
Resources
jackson json
spring boot
Return xml from REST request
as a serious violation. Please provide the justification below and click continue option .*Access shall be enabled for 1 hour:
Justification :
Personal Business Research
Continue
Click Go Back or use the browser's Back button to return to the previous page. Go Back
After making a GET request to a REST service the natural progression is to POST information back to the server. In this
episode we will look at how to post json to spring controller and have it automatically convert JSON to arraylist, object
or multiple objects.
Understanding @RequestBody
The 峒\rst thing to understand is how json binds to a java object. The @RequestBody method parameter annotation
should bind the json value in the HTTP request body to the java object by using a HttpMessageConverter. In episode 13
how to return XML in REST, we discussed the responsibility of HttpMessageConverter. To recap
HttpMessageConverter is responsible for converting the HTTP request message to an assoicated java object. In our
case want to convert JSON to a java object when a request is made. Spring will look speci峒\cally for a
HttpMessageConverter assoicated to the mime type to perform the conversion. Since spring boot con峒\gures it
automatically if jackson is on our class path MappingJackson2MessageConverter is used. Alternatively you can
http://www.leveluplunch.com/java/tutorials/014postjsontospringrestwebservice/ 2/18
6/3/2016 Post JSON to spring REST webservice | Level Up Lunch
con峒\gure GsonHttpMessageConverter based on google gson library which was o䎛耀cally release in spring version 4.1.
In code we annotate the method parameter with spring @RequestBody which looks like:
Project set up
[1:15]
Creating a project
We will create a new project with spring boot and create a POJO object Car which will post to a spring controller. One
thing to note in our snippets is we won't discuss REST api design topic or make the actual update to a persistence
layer.
//...
}
Get request
http://www.leveluplunch.com/java/tutorials/014postjsontospringrestwebservice/ 3/18
6/3/2016 Post JSON to spring REST webservice | Level Up Lunch
Get request
[1:56]
Before we post JSON, lets create a method to return a Car and make a request to http://localhost:8080/. You will notice
that we are using ResponseEntity as the method return type. ResponseEntity is a class that allows you to modify
request and response headers. An important design aspect of REST services is also to return the proper HTTP status
code and in this case a 200.
@RequestMapping(value = "/")
public ResponseEntity<Car> get() {
{
color: "Blue"
miles: 100
vin: "1234"
}
You might want to update the Car object by posting json to a URL. A more detailed user story would be, as a user I
want to be able update attributes of my car. We will create @RequestMapping and specify method =
RequestMethod.POST which will tell spring to use this method when a post occurs. When the post is made lets
increment the miles by 100.
if (car != null) {
car.setMiles(car.getMiles() + 100);
}
Using the sample JSON above, lets make a request using advanced rest client chrome plugin and result should
increment the miles 峒\eld by 100.
{
"color":"Blue",
"miles":200,
"vin":"1234"
}
Json to arraylist
http://www.leveluplunch.com/java/tutorials/014postjsontospringrestwebservice/ 5/18
6/3/2016 Post JSON to spring REST webservice | Level Up Lunch
Json to arraylist
[2:48]
Next, you might have a life event where you inherit a car, get married or your child starts to drive (good luck!). Now we
have a series of cars we want to update the mileage. Lets create a new request mapping to http://localhost:8080/cars
which accepts a json array as a parameter. Again, we will increment mileage by 100 using a java 8 foreach loop.
Modi峒\ng our sample json above we will convert it to a json array and add an additonal node. Lets make a request
using advanced rest client chrome plugin and we should see the miles increment by 100.
[
{
"color":"Blue",
"miles":200,
"vin":"1234"
},
{
"color":"Red",
"miles":500,
http://www.leveluplunch.com/java/tutorials/014postjsontospringrestwebservice/ 6/18
6/3/2016 Post JSON to spring REST webservice | Level Up Lunch
"vin":"1235"
}
]
If you want to send multiple json objects to a controller, you will need to create a wrapper object that represents your
request due to the request containing the entire JSON content. We will create a Truck object, a RequestWrapper object
and a new @RequestMapping.
Truck object
//...
}
RequestWrapper object
The RequestWrapper will contain a List of Cars and a single truck object.
http://www.leveluplunch.com/java/tutorials/014postjsontospringrestwebservice/ 7/18
6/3/2016 Post JSON to spring REST webservice | Level Up Lunch
List<Car> cars;
Truck truck;
//...
}
New @RequestMapping
requestWrapper.getCars().stream()
.forEach(c ‐> c.setMiles(c.getMiles() + 100));
http://www.leveluplunch.com/java/tutorials/014postjsontospringrestwebservice/ 8/18
6/3/2016 Post JSON to spring REST webservice | Level Up Lunch
"cars":[
{
"color":"Blue",
"miles":100,
"vin":"1234"
},
{
"color":"Red",
"miles":400,
"vin":"1235"
}
],
"truck":{
"color":"Red",
"miles":400,
"vin":"1235"
}
}
Post JSON to spring REST webservice posted by Justin Musgrove on 22 August 2014
All the code on this page is available on github: View the source
I tried the same example but it is giving me "415 Unsupported Media Type" error
import java.util.List;
public class UserWrapper {
private List<user> users;
public List<user> getUsers() {
return users;
}
public void setUsers(List<user> users) {
this.users = users;
}
}
△ ▽ • Reply • Share ›
http://www.leveluplunch.com/java/tutorials/014postjsontospringrestwebservice/ 11/18
6/3/2016 Post JSON to spring REST webservice | Level Up Lunch
In json to arraylist
/* here if write cars.get(0) I can get the first object.But Sir my objective is to get the color of the each object.I tried somthing like
this cars.get(0).getColor(); but get an error.Sir what should I need to have the color separately i.e if my json is like below
[
{
"color":"Blue",
"miles":200,
"vin":"1234"
},
{
"color":"Red",
http://www.leveluplunch.com/java/tutorials/014postjsontospringrestwebservice/ 12/18
6/3/2016 Post JSON to spring REST webservice | Level Up Lunch
"color":"Red",
"miles":500,
"vin":"1235"
}
]
then I want to Blue and Red, cars.get(0).getColor(); is not working then how to do this. */
}
△ ▽ • Reply • Share ›
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class ModelPessoa extends UtilBaseEntities<long>// . . .
The Entity:
@Entity
@Table(name = "aluno")
public class EntityAluno extends ModelPessoa / / . . .
@Entity
@Table(name = "usuario")
public class EntityUsuario extends UtilBaseEntities<long> / / . . .
@OneToOne
see more
△ ▽ • Reply • Share ›
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class ModelPessoa extends UtilBaseEntities<long>// . . .
A Entity:
@Entity
@Table(name = "aluno")
public class EntityAluno extends ModelPessoa / / . . .
@Entity
@Table(name = "usuario")
public class EntityUsuario extends UtilBaseEntities<long> / / . . .
see more
△ ▽ • Reply • Share ›
Is this what you were looking for or was there something more specific?
△ ▽ • Reply • Share ›
Object {
EmbeddedOutput embeddedOutput;
}
△ ▽ • Reply • Share ›
http://www.leveluplunch.com/java/tutorials/014postjsontospringrestwebservice/ 16/18
6/3/2016 Post JSON to spring REST webservice | Level Up Lunch
"commands": [
"insert": {
"object": {
"jai1.droolstest.ItemCity":
"purchaseCity":"NAGPUR",
"sellPrice":"10",
"localTax":"1.0",
see more
△ ▽ • Reply • Share ›
http://www.leveluplunch.com/java/tutorials/014postjsontospringrestwebservice/ 17/18
6/3/2016 Post JSON to spring REST webservice | Level Up Lunch
This work is licensed under a Creative Commons Attribution 3.0 Unported License.
http://www.leveluplunch.com/java/tutorials/014postjsontospringrestwebservice/ 18/18