@JsonProperty in Spring Boot to change the key in the output json.

TECH WOLF
1 min readMay 24, 2022

In Springboot we often would come in situation where we want the json key of the filed to be changed to something else. Let take an example. In the DB we have three fields. Dept, class, subclass for an item.

Now, Since in Java class is a reserved keyword. So by default it would not allow to make you a variable with name class. But the thing is what if the person consuming your message wants it to be class. Well for this kind of situation only we have the concept of formatting the json messgae.

@JsonProperty. Its part of the library.

com.fasterxml.jackson.annotation.JsonProperty;

Example Code of JsonProperty:

package com.app.web.parasmani.Schooler.model;

import com.fasterxml.jackson.annotation.JsonProperty;

public class School {
String schoolName;
Integer schoolNo;

public School() {
}

public School(String schoolName, Integer schoolNo) {
this.schoolName = schoolName;
this.schoolNo = schoolNo;
}

@JsonProperty("school")
public String getSchoolName() {
return schoolName;
}

@JsonProperty("school")
public void setSchoolName(String schoolName) {
this.schoolName = schoolName;
}

@JsonProperty("registrationNumber")
public Integer getSchoolNo() {
return schoolNo;
}

@JsonProperty("registrationNumber")
public void setSchoolNo(Integer schoolNo) {
this.schoolNo = schoolNo;
}
}

Over here we have put the jsonProperty over getter and setter get out desired json.

Over here in the example although, the variable name is schoolName, schoolNo but than also it would be overridden by the @jsonproperty.

like below:

[
{
"school": "ABC Public School",
"registrationNumber": 1234
}
]

Ok, done for the day!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

--

--