简体   繁体   English

Gson:将Json反序列化为Abstract类

[英]Gson: Deserialize Json into Abstract Class

I have json that contains: 我有包含以下内容的json:

{"timeZone": "America/Los_Angeles"}

among many other keys, and I want to deserialize it into java.util.TimeZone . 以及其他许多键中,我想将其反序列化为java.util.TimeZone TimeZone is just a field in a class that I want to instantiate with this json. TimeZone只是我想用此json实例化的类中的一个字段。

The issue is that TimeZone is an abstract class and it should be instantiated with: 问题在于TimeZone是一个抽象类,应使用以下方法实例化:

public static synchronized TimeZone getTimeZone(String ID) {
        return getTimeZone(ID, true);

which uses a concrete class ZoneInfo to instantiate. 它使用具体的类ZoneInfo实例化。 The deserializer, however, calls the constructor of TimeZone by default. 但是,解串器默认情况下会调用TimeZone的构造函数。 So I got: 所以我得到了:

java.lang.RuntimeException: Failed to invoke public java.util.TimeZone() with no args

I wonder how to configure Gson to instantiate a TimeZone from the above json? 我想知道如何配置Gson以从上述json实例化TimeZone

You'd need to create something like a Gson TypeAdapter and register it with your Gson instance. 您需要创建类似Gson TypeAdapter并将其注册到Gson实例。

I'm not sure how/whether this will work for your particular data format, but here's an example that I've used in my own projects: 我不确定这将如何/是否适用于您的特定数据格式,但这是我在自己的项目中使用的示例:

public class TimeZoneAdapter extends TypeAdapter<TimeZone> {
  @Override
  public void write(JsonWriter out, TimeZone value) throws IOException {
    out.value(value.getID());
  }

  @Override
  public TimeZone read(JsonReader in) throws IOException {
    return TimeZone.getTimeZone(in.nextString());
  }
}

You would then register it when building a Gson instance like so: 然后,您将在构建Gson实例时注册它,如下所示:

GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(TimeZone.class, new TimeZoneAdapter());

Gson gson = builder.create();

Hope this helps! 希望这可以帮助!

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

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