【问题标题】:how to De-serialize a List<Generic<Enum>> using Gson library如何使用 Gson 库反序列化 List<Generic<Enum>>
【发布时间】:2020-07-24 17:36:05
【问题描述】:

我需要将这个 Json 字符串反序列化为 POJO。

json:

[
    {
        "first" : {
            "value" : 12,
            "suit" :  {
                "name" : "heart"
            }
        },

        "second" : {
            "value" : 12,
            "suit" : {
                "name" : "spade"
            }
        }
    },
    {
        "first" : {
            "value" : 8,
            "suit" : {
                "name" : "club"
            }
        },
        "second" : {
            "value" : 9,
            "suit" : {
                "name" : "club"
            }
        }
    }
]

我正在尝试将此 json 字符串反序列化为 ArrayList&lt;Pair&lt;Card&gt;&gt;,其中 Pair&lt;?&gt; 类是通用的,Card 类是枚举。

我正在尝试通过以下方式做到这一点:

Type listType = new TypeToken<ArrayList<Pair<Card>>>(){}.getType();
List<Pair<Card>> handList = gson.fromJson(hands, listType);

卡类:

public enum Card {


@SerializedName("value")
public int value;
@SerializedName("suit")
public Suit suit;

Card(int value, Suit suit) {
    this.value = value;
    this.suit = suit;
}

西装等级:

public enum Suit {


@SerializedName("name")
public String name;

Suit(String name) {
    this.name = name;
}

}

但是 Gson 一直在抛出 IllegalStateException's

java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 3 column 15 path $[0].first

【问题讨论】:

  • 因为你期待一个String,但你得到的是一个对象。
  • 是的,但这确实没有帮助
  • 告诉我们你Card类。并且和{ "value" : 9,"suit" : {"name" : "club"}}这个结构匹配?
  • 你没有在枚举类中定义任何枚举?
  • @NateSchreiner 我不明白你为什么选择枚举而不是普通类?枚举类表示您的类中缺少的一组常量Ex

标签: java json gson typetoken


【解决方案1】:

您可以为Card 类创建自定义反序列化器

public class CardDeserializer implements JsonDeserializer<Card> {
    @Override
    public Card deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        JsonObject obj = json.getAsJsonObject();
        JsonObject jobject = obj.getAsJsonObject("suit");
        //Create Card here using those value
        //obj.get("value").getAsString();
        //jobject.get("name").getAsString();
        ...
        return card;
    }
}

工作前在gson builder中注册

gson.registerTypeAdapter(Card.class, new CardDeserializer());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2017-01-21
    • 2013-02-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    相关资源
    最近更新 更多