如何使用Spring Boot将JSON映射到对象

编程入门 行业动态 更新时间:2024-10-11 21:27:52
本文介绍了如何使用Spring Boot将JSON映射到对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

你好,我想知道在使用Spring Boot时如何将json消息映射到java中的对象.

Hello I'd like to know how I could mapp my json message to object in java when using spring boot.

让我说我正在获取json

Let's say I'm getting json like

{ "customerId": 2, "firstName": "Jan", "lastName": "Nowak", "town": "Katowice" }

,我想在我的java程序中使其成为实体: 出于任何原因,我都不希望字段名匹配

and I'd like to make it entity in my java program: and for whatever reason I dont want to have match on field names

public class Customer { //Something like @Map("customerId") private long OMG; //Something like @Map("firstName") private String WTF; //Something like @Map("lastName") private String LOL; //Something like @Map("town") private String YOLO;

我找不到应该使用的注释,不是使用杰克逊,而是内置在spring boot转换器中?

I cannot find what annotation I should use, Not using jackson, just built in spring boot converter??

推荐答案

Jackson开箱即用,提供了春季启动功能.

Spring boot comes with Jackson out-of-the-box.

您可以使用@RequestBody Spring MVC批注将json字符串解编组到Java对象中...

You can use @RequestBody Spring MVC annotation to un-marshall json string to Java object... something like this.

@RestController public class CustomerController { //@Autowired CustomerService customerService; @RequestMapping(path="/customers", method= RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) public Customer postCustomer(@RequestBody Customer customer){ //return customerService.createCustomer(customer); } }

使用@JsonProperty和相应的json字段名称注释您的实体成员元素.

Annotate your entities member elements with @JsonProperty with corresponding json field names.

public class Customer { @JsonProperty("customerId") private long OMG; @JsonProperty("firstName") private String WTF; @JsonProperty("lastName") private String LOL; @JsonProperty("town") private String YOLO; }

更多推荐

如何使用Spring Boot将JSON映射到对象

本文发布于:2023-11-26 08:47:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1633433.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   对象   Boot   Spring   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!