you can use GSON annotation @SerializedName annotation for using a different names for serialized fields.
Maven Dependency Needed:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency> For Example:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;
public class GsonExposeAnnotationTest {
public static void main(String[] args) {
Student student = new Student("Dinesh", "ROLL123", "Hyderabad - 500081");
Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson(student));
}
}
class Student {
@SerializedName("student-name")
String name;
@SerializedName("student-rollno")
String rollNo;
@SerializedName("student-address")
String address;
public Student(String name, String rollNo, String address) {
this.name = name;
this.rollNo = rollNo;
this.address = address;
}
} Output: Serialised output - fields name are different than in POJO { "student-name": "Dinesh", "student-rollno": "ROLL123", "student-address": "Hyderabad - 500081" }
No comments:
Post a Comment