简体   繁体   中英

how to De-serialize a List<Generic<Enum>> using Gson library

I need to De-serialize this Json string into a 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"
            }
        }
    }
]

I am trying to de-serialize this json string to a ArrayList<Pair<Card>> where the Pair<?> class is generic and the Card class is an enum.

I am attempting to do this via the following:

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

Card class:

public enum Card {


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

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

Suit class:

public enum Suit {


@SerializedName("name")
public String name;

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

}

However Gson keeps throwing IllegalStateException 's

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

You can create a custom Deserializer for Card class

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;
    }
}

And register in gson builder before work

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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