【问题标题】:How to evaluate json string containing enum value?如何评估包含枚举值的json字符串?
【发布时间】:2019-07-19 02:20:29
【问题描述】:

我有一个看起来像这样的枚举

public enum Example {
    EXAMPLE_1,
    EXAMPLE_2,
    EXAMPLE_3,
}

我正在尝试解析这样的 json 字符串:

String json = "{\"blah\": \"Example.EXAMPLE_1\"}"

我尝试过这样定义一个类:

public class Blah {
    Example blah;
}

并使用

gson.fromJson(json, Blah.class)

但它只是将字段设置为空。有没有办法做到这一点?不幸的是,我无法控制 json 字符串的格式,所以我必须按原样解析它。

【问题讨论】:

    标签: java json enums gson


    【解决方案1】:

    默认 gson 将解析没有类名的枚举字段。您可以为 Example 枚举自定义您自己的 json 反序列化器。

    JsonDeserializer<?> jd = new JsonDeserializer<Example>() {
      @Override
      public Example deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        String enumStr = json.getAsString();
        String enumVal = enumStr.split("\\."); // etc...
        Example val = ... ...
        //...
    
        return val;
      }
    };
    
    Gson gson = new GsonBuilder().registerTypeAdapter(Example.class, jd).create();
    

    【讨论】:

      【解决方案2】:

      试试这个json

      String json = "{\"blah\": \"EXAMPLE_1\"}"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-04-25
        • 1970-01-01
        • 2014-06-21
        • 2014-08-09
        • 2019-03-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多