
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
30
Gson @SerializedName 注释 可以序列化为 JSON,并将提供的名称值作为其字段名称。此注释可以覆盖任何 FieldNamingPolicy,包括可能已在 Gson 实例上设置的默认字段命名策略。可以使用GsonBuilder类设置不同的命名策略。
@Retention(value=RUNTIME)
@Target(value={FIELD,METHOD})
public @interface SerializedNameimport 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");
<strong>Gson </strong>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")<strong>
</strong> 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的属性?的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号