1

Java class (used as a Data Transfer Object):

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; }
}

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.

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?

Rushil Paul
  • 2,010
  • 4
  • 26
  • 39

2 Answers2

2

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;
    }
}

Tested it with this:

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

And the output was:

{
  "_id_": "id1",
  "id": 1
}
Community
  • 1
  • 1
Shawn Clark
  • 3,330
  • 2
  • 18
  • 30
1
public A extends Resource {
    private int id;

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

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

the method names should be different, so jackson parses it as different fields, not as one field.

jarvo69
  • 7,908
  • 2
  • 18
  • 28