0% found this document useful (0 votes)
9 views18 pages

Post JSON To Spring REST Webservice - Level Up Lunch

This document provides a tutorial on how to post JSON data to a Spring REST web service. It explains the use of the @RequestBody annotation to bind JSON to Java objects, demonstrates creating a project with Spring Boot, and shows how to handle both single and multiple JSON objects in requests. The tutorial includes code examples for updating a 'Car' object and handling arrays of 'Car' objects, as well as a wrapper object for multiple JSON types.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views18 pages

Post JSON To Spring REST Webservice - Level Up Lunch

This document provides a tutorial on how to post JSON data to a Spring REST web service. It explains the use of the @RequestBody annotation to bind JSON to Java objects, demonstrates creating a project with Spring Boot, and shows how to handle both single and multiple JSON objects in requests. The tutorial includes code examples for updating a 'Car' object and handling arrays of 'Car' objects, as well as a wrapper object for multiple JSON types.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

6/3/2016 Post JSON to spring REST webservice | Level Up Lunch

M≡NU

Post JSON to spring REST webservice

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

Please ensure NOT TO:


1. Access, download, transmit or display offensive, sexually
http://www.leveluplunch.com/java/tutorials/014­post­json­to­spring­rest­webservice/ explicit, profane, racist, defamatory or unlawful content. 1/18
6/3/2016 Post JSON to spring REST webservice | Level Up Lunch
1. Access, download, transmit or display offensive, sexually explicit, profane, racist, defamatory or unlawful content.
2. Use groups, mailing lists, blogs and other forums on the internet to inappropriately disclose information about or discuss matters
related to Cognizant or clients.
3. Use high­bandwidth related applications such as streaming media, internet radio, etc. for non­business purposes.

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.

Detailed Video Notes

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/014­post­json­to­spring­rest­webservice/ 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:

@RequestMapping(value = "/", method = RequestMethod.POST)


public ResponseEntity<Car> update(@RequestBody Car car) {
...
}

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.

public class Car {

private String VIN;


private String color;
private Integer miles;

//...
}

Get request
http://www.leveluplunch.com/java/tutorials/014­post­json­to­spring­rest­webservice/ 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() {

Car car = new Car();


car.setColor("Blue");
car.setMiles(100);
car.setVIN("1234");

return new ResponseEntity<Car>(car, HttpStatus.OK);


}

Which should return a json response:

{
color: "Blue"
miles: 100
vin: "1234"
}

Json to java object


http://www.leveluplunch.com/java/tutorials/014­post­json­to­spring­rest­webservice/ 4/18
6/3/2016 Post JSON to spring REST webservice | Level Up Lunch

Json to java object


[2:2]

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.

@RequestMapping(value = "/", method = RequestMethod.POST)


public ResponseEntity<Car> update(@RequestBody Car car) {

if (car != null) {
car.setMiles(car.getMiles() + 100);
}

// TODO: call persistence layer to update


return new ResponseEntity<Car>(car, HttpStatus.OK);
}

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/014­post­json­to­spring­rest­webservice/ 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.

@RequestMapping(value = "/cars", method = RequestMethod.POST)


public ResponseEntity<List<Car>> update(@RequestBody List<Car> cars) {

cars.stream().forEach(c ‐> c.setMiles(c.getMiles() + 100));

// TODO: call persistence layer to update


return new ResponseEntity<List<Car>>(cars, HttpStatus.OK);
}

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/014­post­json­to­spring­rest­webservice/ 6/18
6/3/2016 Post JSON to spring REST webservice | Level Up Lunch

"vin":"1235"
}
]

Passing multiple json objects


[3:25]

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

public class Truck {

private String VIN;


private String color;
private Integer miles;

//...
}

RequestWrapper object

The RequestWrapper will contain a List of Cars and a single truck object.

http://www.leveluplunch.com/java/tutorials/014­post­json­to­spring­rest­webservice/ 7/18
6/3/2016 Post JSON to spring REST webservice | Level Up Lunch

public class RequestWrapper {

List<Car> cars;
Truck truck;

//...
}

New @RequestMapping

@RequestMapping(value = "/carsandtrucks", method = RequestMethod.POST)


public ResponseEntity<RequestWrapper> updateWithMultipleObjects(
@RequestBody RequestWrapper requestWrapper) {

requestWrapper.getCars().stream()
.forEach(c ‐> c.setMiles(c.getMiles() + 100));

// TODO: call persistence layer to update

return new ResponseEntity<RequestWrapper>(requestWrapper, HttpStatus.OK);


}

Making the request


Again, we will use advanced rest client to http://localhost:8080/carsandtrucks with the following JSON.

http://www.leveluplunch.com/java/tutorials/014­post­json­to­spring­rest­webservice/ 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"
}
}

Thanks for joining in today's level up lunch, have a great day.

Post JSON to spring REST webservice posted by Justin Musgrove on 22 August 2014

Tagged: java, java-tutorial, and spring

Share on: Twitter Facebook Google+

All the code on this page is available on github: View the source

27 Comments Level Up Lunch


http://www.leveluplunch.com/java/tutorials/014­post­json­to­spring­rest­webservice/

1 Login
9/18
6/3/2016 Post JSON to spring REST webservice | Level Up Lunch
27 Comments Level Up Lunch 
1 Login

 Recommend 3 ⤤ Share Sort by Best

Join the discussion…

Kali Prasad Padhy • 5 days ago


Nice Topic, but my question is how to create an client for post request with resttemlate.
△ ▽ • Reply • Share ›

Justin Mod > Kali Prasad Padhy • 5 days ago


@Kali Prasad Padhy check out http://www.leveluplunch.com/ja...
△ ▽ • Reply • Share ›

Agus Suhardi • 11 days ago


how to decode json with ajax??
△ ▽ • Reply • Share ›

Justin Mod > Agus Suhardi • 5 days ago


@Agus Suhardi ­ can you be a bit more specific what you are trying to do?
△ ▽ • Reply • Share ›

Jagsurram Tlt • 3 months ago


Good article.As from my requirement request contains both file and json data what would i have to do?
△ ▽ • Reply • Share ›

Justin Mod > Jagsurram Tlt • 3 months ago


@Jagsurram Tlt check out https://spring.io/guides/gs/up..., we also have a tutorial on how to download a file from rest
template that might give you some pointers. http://www.leveluplunch.com/ja...
△ ▽ • Reply • Share ›

Swapnil Lungade • 4 months ago


http://www.leveluplunch.com/java/tutorials/014­post­json­to­spring­rest­webservice/ 10/18
6/3/2016 Post JSON to spring REST webservice | Level Up Lunch

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;
}
}

@RequestMapping(value = "editUser", method = RequestMethod.POST,


consumes="application/json",produces="application/json")
@ResponseBody
public String updateUser(@RequestBody UserWrapper users) {
for(User user:users.getUsers()){
if (user.getId() > 0) {
see more

△ ▽ • Reply • Share ›

Rahul Bhalerao • 4 months ago


I tried following the instructions and used chrome's postman to post json data to spring controller directly. Not that, there is no
web page associated to the controller. Controller should directly respond to a URL. This may be a stupid query, but '404 ­ not
found' is being thrown when the JSON is posted to the URL mapped with the controller. Am I missing something? Is webpage
required to be present on the given URL for webservice to work?
△ ▽ • Reply • Share ›

Amit • 9 months ago


Hi , Thanks for the post. While consuming post method, my Json is encoded using java script encodeURIComponent(), In that
case Spring json converter is failing to convert post http entity to Pojo. Any idea, how to handle this case?
△ ▽ • Reply • Share ›

http://www.leveluplunch.com/java/tutorials/014­post­json­to­spring­rest­webservice/ 11/18
6/3/2016 Post JSON to spring REST webservice | Level Up Lunch

Андрей Москвичёв • 10 months ago


Thank you!
△ ▽ • Reply • Share ›

Krishna • 10 months ago


Thanks for the post. It was very much useful.
△ ▽ • Reply • Share ›

Justin Mod > Krishna • 10 months ago


Your welcome, hope it helped!
△ ▽ • Reply • Share ›

Mithun Debnath • a year ago


Hello Sir,

In json to arraylist

@RequestMapping(value = "/cars", method = RequestMethod.POST)

public ResponseEntity<list<car>> update(@RequestBody List<car> cars) {

return new ResponseEntity<list<car>>(cars, HttpStatus.OK);

/* 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/014­post­json­to­spring­rest­webservice/ 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 ›

felansu • a year ago


Hello ! I'm using Spring Boot, and i have the next problem:

Have a class model:

@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 / / . . .

and the class User with person (pessoa):

@Entity
@Table(name = "usuario")
public class EntityUsuario extends UtilBaseEntities<long> / / . . .
@OneToOne
see more

△ ▽ • Reply • Share ›

Guest • a year ago


http://www.leveluplunch.com/java/tutorials/014­post­json­to­spring­rest­webservice/ 13/18
6/3/2016 Post JSON to spring REST webservice | Level Up Lunch
Guest • a year ago
Hello ! I'm using Spring Boot, and i have the next problem:

Have a class model:

@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 / / . . .

and the class User with person (pessoa):

@Entity
@Table(name = "usuario")
public class EntityUsuario extends UtilBaseEntities<long> / / . . .

see more

△ ▽ • Reply • Share ›

Meriem Elouragini • a year ago


how to consume JSON in spring boot ?
△ ▽ • Reply • Share ›

Justin Mod > Meriem Elouragini • a year ago


If you want to use java and spring as a client to call a REST service check out http://www.leveluplunch.com/ja... OR you
could consume it with http client http://www.leveluplunch.com/ja...

Is this what you were looking for or was there something more specific?
△ ▽ • Reply • Share ›

Meriem Elouragini > Justin •


http://www.leveluplunch.com/java/tutorials/014­post­json­to­spring­rest­webservice/ a year ago 14/18
6/3/2016 Post JSON to spring REST webservice | Level Up Lunch
Meriem Elouragini > Justin • a year ago
yeah , my problem is solved already, thanks alot
△ ▽ • Reply • Share ›

geezenslaw • a year ago


OK. I didn't POST as JSON ARRAY using [] as implicitly suggested.
△ ▽ • Reply • Share ›

Justin Mod > geezenslaw • a year ago


Glad you got it figured out...
△ ▽ • Reply • Share ›

geezenslaw • a year ago


Howdy, everything went great after cloning the project and running with path / and GET and POST with the prescribed JSON.
However, changing the path to /cars and POST with the same JSON I get the following exception.

nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList


out of START_OBJECT token

I have googled this to pieces w/o any real progress.

Any ideas or suggestions for diagnostics welcomed.


△ ▽ • Reply • Share ›

Paddu • a year ago


Thanks for the sample. I have requirement to POST a file via REST call and get the response (via JSON, along with the file).
Just wondering how to write the POJO for the below which has an array with an array
{
"ProcessedFile":"samplestring1",
"ProcessingTime":2,
"EmbeddedOutput":{
"InputFileName":"samplestring1",
"InputFileSize":2,
"OutputFileSize":3,
http://www.leveluplunch.com/java/tutorials/014­post­json­to­spring­rest­webservice/ 15/18
6/3/2016 Post JSON to spring REST webservice | Level Up Lunch
"OutputFileSize":3,
"Timestamp":"samplestring4",
"ElapsedTimeMs":5,
"TransactionId":10,
"CreatorId":11
}
}
△ ▽ • Reply • Share ›

Justin Mod > Paddu • a year ago


Hey Paddu, this tutorial doesn't handle uploading a file but with a little work and research on multipartfile you could get
there. Without great context to your question, if you wanted to pass along the json you have outlined you could wrap the
object like. Hope this helps

Object {
EmbeddedOutput embeddedOutput;
}

△ ▽ • Reply • Share ›

Andrushka • 2 years ago


Thanks a lot, great lesson (I mean lunch).

I notice that @JsonProperty("VIN") on setter helps me post JSON as


{
"color": "Blue",
"miles": 10780,
"VIN": "777888"
}
△ ▽ • Reply • Share ›

Justin Mod > Andrushka • 2 years ago


Glad you liked it... Yes this is a very helpful jackson annotation...
△ ▽ • Reply • Share ›

http://www.leveluplunch.com/java/tutorials/014­post­json­to­spring­rest­webservice/ 16/18
6/3/2016 Post JSON to spring REST webservice | Level Up Lunch

Jai Nath Gupta > Justin • 3 months ago


PASS MULTIPLE OBJECT IN ARC FOR DROOLS CONTAINER :­

"commands": [

"insert": {

"object": {

"jai1.droolstest.ItemCity":

"purchaseCity":"NAGPUR",

"sellPrice":"10",

"localTax":"1.0",
see more

△ ▽ • Reply • Share ›

Justin Mod > Jai Nath Gupta • 3 months ago


@Jai Nath Gupta did you hit the post button to quick, what is it you are asking or commenting on?
△ ▽ • Reply • Share ›

✉ Subscribe d Add Disqus to your site Add Disqus Add ὑ Privacy

http://www.leveluplunch.com/java/tutorials/014­post­json­to­spring­rest­webservice/ 17/18
6/3/2016 Post JSON to spring REST webservice | Level Up Lunch

About us ▪ Blog ▪ Style Guide


Exercises ▪ Examples ▪ Tutorials

This work is licensed under a Creative Commons Attribution 3.0 Unported License.

http://www.leveluplunch.com/java/tutorials/014­post­json­to­spring­rest­webservice/ 18/18

You might also like