Home > Back-end >  Add alias symbol to class variable in Java
Add alias symbol to class variable in Java

Time:12-12

I am having a requirement to develop a JSON formatted data to pass to our 3rd party API vendor. One of the parameters require the variable to have alias symbol in front, but I am unsure the best way to put it.

JSON Example

"Test": [
            {
                "name": "1",
                "@type": "2"
            }
        ],

JAVA test class

public class Test
{
    private String name;
    private String type;
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
}

How do I have the "@" symbol in front of the "type" variable? Any help is greatly appreciated.

CodePudding user response:

Assuming you have that weird requirement (which makes no sense to me) you can always change the name of a field that is serialized to JSON by using the JsonProperty annotation (assuming you are using Jackson of course).

To achieve something like that, simply do something in the lines of:

public class Test {

    private String name;
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @JsonProperty("@type")
    private String type;
    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

}
  • Related