1

I have a class definition say

class Employee {
 String id;
 String name;
 int age;
 //getters and setters
}

I want to create a json object out of it as follows

{
  "id" : "A12",
  "employee_name" : "Abhishek"
  age : 97
}

Notice that employee_name does not correspond to POJO variable name. So can I add certain annotation which will help me do so ? Something Like

@JSONKey(value="employee_name")
String name

Give solutions related to GSON and/or Jackson.

Abhishek Singh
  • 10,243
  • 22
  • 74
  • 108

3 Answers3

13

In Jackson use @JsonProperty

E.g.:

@JsonProperty(value="employee_name")
String name

with GSON use @SerializedName

@SerializedName(value="employee_name")
String name
Sachin Gupta
  • 7,805
  • 4
  • 30
  • 45
  • You saved my time bro, thanks a lot. I was using @JsonProperty for GSON, I didn't realize I was using the wrong implantation. I used @SerializedName("jsonFieldName") for GSON and It solved my problem. Thansk again. – Semih Erkaraca Nov 29 '22 at 11:40
0

With Gson you can use the @SerializedName annotation

@SerializedName("employee_name")
String name;
jadec
  • 26
  • 6
0

You can use @JsonProperty for Jackson: Change field name in JSON using Jackson

And @SerializedName for Gson: Convert JSON style properties names to Java CamelCase names with GSON

No Em
  • 59
  • 5