文章17 | 阅读 10170 | 点赞0
本文内容大多基于官方文档和网上前辈经验总结,经过个人实践加以整理积累,仅供参考。
1 新建包含内部类的 POJO 类
public class User {
private String account;
private String password;
private String name;
private int age;
private Address address;
public User() {}
public User(String account, String password, String name, int age, double longtitude, double latitude) {
this.account = account;
this.password = password;
this.name = name;
this.age = age;
this.address = new Address();
this.address.setLongtitude(longtitude);
this.address.setLatitude(latitude);
}
public class Address {
private double longtitude;
private double latitude;
public double getLongtitude() {
return longtitude;
}
public void setLongtitude(double longtitude) {
this.longtitude = longtitude;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
@Override
public String toString() {
return "Address [longtitude=" + longtitude + ", latitude=" + latitude + "]";
}
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString() {
return "User [account=" + account + ", password=" + password + ", name=" + name + ", age=" + age + ", address="
+ address + "]";
}
}
2 测试代码
@Test
public void test() throws IOException {
User user = new User("ACCOUNT", "PASSWORD", "NAME", 25, 99.9999, 111.1111);
Gson gson = new Gson();
System.out.println(gson.toJson(user));
gson = new GsonBuilder()
.disableInnerClassSerialization()
.create();
System.out.println(gson.toJson(user));
}
运行结果:
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/Silent_Paladin/article/details/54097795
内容来源于网络,如有侵权,请联系作者删除!