Object to Json String
Java Json 2017
package com.gson.json; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.annotations.SerializedName; public class ObjectToJsonString { public static void main(String a[]) { Employee emp = new Employee(); emp.setEmpId(9999); emp.setName("Antonio"); emp.setSalary(29000); emp.setDesignation("Manager"); emp.setDepartment("Accounts"); Gson gsonObj = new GsonBuilder().setPrettyPrinting().create(); // converts object to json string String jsonStr = gsonObj.toJson(emp); System.out.println(jsonStr); } } class Employee { @SerializedName("emp_id") private int empId; @SerializedName("emp_name") private String name; private String designation; private String department; private int salary; public int getEmpId() { return empId; } public void setEmpId(int empId) { this.empId = empId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDesignation() { return designation; } public void setDesignation(String designation) { this.designation = designation; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } }
Chú ý empId và name có @SerializedName("emp_id") @SerializedName("emp_name")
0 nhận xét:
Post a Comment