我正在使用Gson库的@JsonAdapter注释将我的JSON对象序列化/反序列化为POJO。
反序列化工作正常,但序列化给了我这个
{
"name": "ana",
"email": "test@test.co.uk",
"address": {
"address_line1": "123 Some Address",
"address_line2": "",
"address_city": "My city",
"address_postalcode": "CV31 9GP"
}
}
而不是
{
"name": "ana",
"email": "test@test.co.uk",
"address_line1": "123 Some Address",
"address_line2": "",
"address_city": "My city",
"address_postalcode": "CV31 9GP"
}
这是因为我正在返回一个JsonElement,但我看不到另一种序列化我的Address对象的方法。
有没有办法返回外键值对?
User.java:
public class User() {
private String name;
private String email;
@JsonAdapter(AddressSerializer.class)
private Address address;
...
}
AddressSerializer.java
public class AddressSerializer implements JsonSerializer<Address> {
@Override
public JsonElement serialize(Address src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject jsonAddress = new JsonObject();
jsonAddress.addProperty("address_line1", src.getAddressLine1());
jsonAddress.addProperty("address_line2", src.getAddressLine2());
jsonAddress.addProperty("address_city", src.getCity());
jsonAddress.addProperty("address_postalcode", src.getPostcode());
return jsonAddress;
}
}
答案 0 :(得分:0)
你试过@JsonUnwrapped吗?
编辑:但是,因为@srinu指出你现在得到的JSON是标准表示,它表明Address是一个不同的对象。否则看起来所有属性都属于用户。
答案 1 :(得分:0)
似乎与this问题有关。
您可以为用户序列化程序执行类似的操作:
public class UserSerializer implements JsonSerializer<User> {
@Override
public JsonElement serialize(User src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject jsonUser = new JsonObject();
jsonUser.addProperty("name", src.getName());
jsonUser.addProperty("email", src.getEmail());
jsonUser.addProperty("address_line1", src.getAddress().getAddressLine1());
jsonUser.addProperty("address_line2", src.getAddress().getAddressLine2());
jsonUser.addProperty("address_city", src.getAddress().getCity());
jsonUser.addProperty("address_postalcode", src.getAddress().getPostcode());
return jsonUser;
}
}