Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add alias symbol to class variable in Java

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading