简体   繁体   English

如何从只读基础 class 覆盖 JSON 字段并改用子字段?

[英]How to override JSON field from read-only base class and use child field instead?

I have a base class (read-only) to fetch data from external API:我有一个基础 class(只读)来从外部 API 获取数据:

public class Manager {
 // so many fields
 public User user;
 // ...
}

Since field user is lost some fields, so I need to create new User class.由于字段用户丢失了一些字段,所以我需要创建新用户 class。

public class NewUser extends com.readonly.User {

    public String avatarUrl;
    public String fullname;
    public String address;
    // ....
}

Then I create NewManager and use it to fetch data from API.然后我创建NewManager并使用它从 API 中获取数据。

public class NewManager extends com.readonly.Manager {
 // so many fields
 public NewUser user;
 // ...
}

But I got Error:但我得到了错误:

java.lang.IllegalArgumentException: class com.sovannarith.model.NewManager declares multiple JSON fields named user
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:172) ~[gson-2.8.6.jar:na]
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:102) ~[gson-2.8.6.jar:na]
    at com.google.gson.Gson.getAdapter(Gson.java:458) ~[gson-2.8.6.jar:na]
    at com.google.gson.Gson.fromJson(Gson.java:931) ~[gson-2.8.6.jar:na]

Note笔记

  • API have field named: user API 有字段名为:用户
  • In both Manager.class and NewManager.class has field named userManager.classNewManager.class中都有名为user的字段
  • I want to use field name user of NewUser.class , not of User.class我想使用NewUser.class的字段名称用户,而不是User.class

Is it possible to do that?有可能这样做吗?

If there is no stringent requirements to use GSON, then try to use Jackson(ObjectMapper), it can serialize objects with same field names.如果没有严格要求使用GSON,那么尝试使用Jackson(ObjectMapper),它可以序列化具有相同字段名的对象。 (Jackson pretty much better IMHO) (杰克逊好多了恕我直言)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM