用于将json字段绑定到POJO中具有不同名称的字段的注释 [英] Annotation for binding a json field to a field in POJO with a different name

查看:507
本文介绍了用于将json字段绑定到POJO中具有不同名称的字段的注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java类(用作数据传输对象):

Java class (used as a Data Transfer Object):

class Resource还具有一个名为id的字段,该字段的类型与getter和setter一样,因此存在语法错误.

class Resource also has a field named id with a different type along with its getter and setter, hence the syntax error.

class A extends Resource
{
   private int id;

   public int getId() { return id; }   // syntax error as getId() function already exists in Resource
   public void setId(int id) { this.id = id; }
}

由于上面的类是DTO,因此将JSON响应(带有字段id)映射到它,并且无法使用getId(),我想将字段更改为_id_并更改getter和setter相应地,并用注解标记它,并将其绑定到id字段.

Since the above class is a DTO, a JSON response (with field id) will be mapped to it, and getId() cannot be used, I want to change the field to _id_ and change getter and setter correspondingly, and mark it with an annotation saying bind this to id field.

注意:我正在使用Spring Boot.我尝试使用@JsonProperty批注,但这没有用.春季有做此操作的注释吗?

Note: I'm using spring boot. I tried using @JsonProperty annotation but that didn't work. Is there an annotation for doing this in spring?

推荐答案

在Googled中找到以下问题:

Googled and found this question: Jackson serialization: how to ignore superclass properties. Adapted it for your problem.

public class A extends B {
    private int id;

    public A(int id) {
        super.setId("id" + id);
        this.id = id;
    }

    @Override
    @JsonProperty("_id_")
    public String getId() {
        return super.getId();
    }

    @Override
    @JsonProperty("_id_")
    public void setId(String id) {
        super.setId(id);
    }

    @JsonProperty("id")
    public int getIntId() {
        return id;
    }

    @JsonProperty("id")
    public void setIntId(int id) {
        this.id = id;
    }
}

public class B {
    private String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}

对此进行了测试:

@RestController
public class TestController {
    @GetMapping("/test")
    public A test() {
        return new A(1);
    }
}

输出为:

{
  "_id_": "id1",
  "id": 1
}

这篇关于用于将json字段绑定到POJO中具有不同名称的字段的注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆