1

I want to create a simple Spring project that will serve as a RESTful service.

I want to send JSON from frontend and want to convert it to a Java object using @RequestBody. After modifying the object in the backend, I need to convert that object back to JSON and send to front end.

How can I achieve this?

warunanc
  • 2,221
  • 1
  • 23
  • 40
Neel
  • 11
  • 1
  • 4

3 Answers3

2

You can use the Jackson library. An example can be found here: http://www.mkyong.com/spring-mvc/spring-3-mvc-and-json-example/

Moritz
  • 41
  • 2
2

Serialization (POJO -> JSON) and deserialization (JSON -> POJO) in Spring is simply obtained via @RequestBody and @ResponseBody annotations.

You just need to define a Java class that represents/maps your JSON object on server-side.

Example:

Input JSON

{id: 123, name: "your name", description: ""}

Java class

public class MyClass {
    private int id;
    private String name;
    private String description;
}

Methods in your controller

public void postJson(@RequestBody MyClass o){
    // do something...
}

public @ResponseBody MyClass getJson(){
    // do something...
}

NOTE I omitted @RequestMapping settings.

davioooh
  • 23,742
  • 39
  • 159
  • 250
0

You will have to provide csrf token for POST request. Instead you can try this.

sending HashMap by angularjs $http.get in spring mvc

It works fine just a bit extra @RequestParams but on the better side you can send additional information too and not only the respective object.

Community
  • 1
  • 1
Kharoud
  • 307
  • 1
  • 7
  • 20