@Retention(value=RUNTIME)
@Target(value={FIELD,METHOD})
public @interface SerializedName
示例
import com.google.gson.annotations.*;
import com.google.gson.*;
public class SerializedNameAnnotationTest {
public static void main(String args[]) {
Employee emp = new Employee("Rahul", "Dev", 30, "Nagpur");
Gson gson = new GsonBuilder().setPrettyPrinting().create(); // pretty print
String jsonStr = gson.toJson(emp);
System.out.println(jsonStr);
}
}
// Employee class
class Employee {
@SerializedName("first_name")
private String firstName;
@SerializedName("last_name")
private String lastName;
private int age;
private String address;
public Employee() {
}
public Employee(String firstName, String lastName, int age, String address) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.address = address;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getAddress() {
return address;
}
}
登录后复制
输出
{
"first_name": "Rahul",
"last_name": "Dev",
"age": 30,
"address": "Nagpur"
}
登录后复制
以上就是如何在Java中使用Gson重命名JSON的属性?的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!