【问题标题】:How to map json to object using spring boot [duplicate]如何使用spring boot将json映射到对象[重复]
【发布时间】:2017-03-06 16:57:41
【问题描述】:

您好,我想知道在使用 spring boot 时如何将我的 json 消息映射到 java 中的对象。

假设我得到了类似的 json

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

我想在我的 java 程序中使它成为实体: 无论出于何种原因,我都不想匹配字段名称

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;

我找不到应该使用什么注释,没有使用jackson,只是内置了spring boot转换器??

【问题讨论】:

  • Spring Boot 对依赖、粘合和默认配置进行分组。它不是序列化 API。您应该使用 Jackson 来满足您的需求

标签: java json spring spring-boot jackson


【解决方案1】:

Jackson 开箱即用的 Spring Boot。

您可以使用 @RequestBody Spring MVC 注释将 json 字符串解组为 Java 对象...类似这样。

@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 字段名称注释您的实体成员元素。

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

【讨论】:

    【解决方案2】:

    Spring Boot 对依赖、粘合和默认配置进行分组。它不是序列化 API。您应该使用 Jackson 来满足您的需求

    你应该映射你的类,例如:

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

    来自 JsonProperty 注解 Javadoc:

    可用于将非静态方法定义为 逻辑属性的“setter”或“getter”(取决于它的 签名),或要使用的非静态对象字段(序列化, 反序列化)作为逻辑属性。

    默认值(“”)表示使用字段名作为 属性名称没有任何修改,但可以指定为 非空值指定不同的名称。属性名称指 外部使用的名称,作为 JSON 对象中的字段名称。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-10
      • 1970-01-01
      • 2014-11-02
      • 2017-02-17
      • 2019-05-27
      • 2022-08-06
      • 2019-12-26
      • 2018-01-18
      相关资源
      最近更新 更多