[英]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. 我想创建一个简单的Spring项目,该项目将用作RESTful服务。
I want to send JSON from frontend and want to convert it to a Java object using @RequestBody
. 我想从前端发送JSON,并想使用
@RequestBody
将其转换为Java对象。 After modifying the object in the backend, I need to convert that object back to JSON and send to front end. 在后端修改对象后,我需要将该对象转换回JSON并发送到前端。
How can I achieve this? 我该如何实现?
You can use the Jackson library. 您可以使用Jackson库。 An example can be found here: http://www.mkyong.com/spring-mvc/spring-3-mvc-and-json-example/
可以在这里找到一个示例: 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. 只需通过
@RequestBody
和@ResponseBody
批注即可获得Spring中的序列化(POJO-> JSON)和反序列化( @ResponseBody
> POJO)。
You just need to define a Java class that represents/maps your JSON object on server-side. 您只需要定义一个Java类,即可在服务器端表示/映射您的JSON对象。
Example: 例:
{id: 123, name: "your name", description: ""}
public class MyClass {
private int id;
private String name;
private String description;
}
public void postJson(@RequestBody MyClass o){
// do something...
}
public @ResponseBody MyClass getJson(){
// do something...
}
NOTE I omitted @RequestMapping
settings. 注意我省略了
@RequestMapping
设置。
You will have to provide csrf token for POST request. 您将必须为POST请求提供csrf令牌。 Instead you can try this.
相反,您可以尝试此。
sending HashMap by angularjs $http.get in spring mvc 在Spring MVC中通过angularjs $ http.get发送HashMap
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. 它只需要额外的@RequestParams就可以了,但是更好的是,您不仅可以发送相应的对象,还可以发送其他信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.