简体   繁体   中英

How to convert a JSON to java object and vice versa in spring controller?

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?

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM