GSON, json in enum. To give meaning to default



  • With help retrofit Received from server json♪ For example:

    ["3","23","3","1","2","11","4"]
    

    Then this joy is desserized into the flow. Enum- Nyuance is that only the number before, let's say, 4. Anything else is interesting, but only as a presence.

    Enum "Kotlin, but it's like Java."

    enum class AccidentDamage(val text: String, val code: Int) {
        @SerializedName("1") WITHOUT("жив, цел, орёл!", 1),
        @SerializedName("2") LIGHT("вроде цел", 2),
        @SerializedName("3") HEAVY("вроде жив", 3),
        @SerializedName("4") LETHAL("летальный", 4),
        UNKNOWN("неизвестно", 255);
    }
    

    I mean, I need to get 1..4 right, and everything else is back as UNKNOWN. For this reason json This flow must be created Enum-So:

    HEAVY,UNKNOWNHEAVY,WITHOUT,LIGHT,UNKNOWNLETHAL

    Is it possible to do this without adapters writing?



  • I don't think so.

    Such behaviour can be carried out with help. https://static.javadoc.io/com.google.code.gson/gson/2.6.2/com/google/gson/JsonDeserializer.html

    private class AccidentDamageDeserializer 
        implements JsonDeserializer<AccidentDamage> {
    

    @Override
    public AccidentDamage deserialize(JsonElement json, Type type,
    JsonDeserializationContext context) throws JsonParseException {
    String damage = json.getAsString();
    switch(damage){
    case "1" : return AccidentDamage.WITHOUT;
    case "2" : return AccidentDamage.LIGHT;
    case "3" : return AccidentDamage.HEAVY;
    case "4" : return AccidentDamage.LETHAL;
    default : return AccidentDamage.UNKNOWN;
    }
    }

    Use it.

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(AccidentDamage.class, new AccidentDamageDeserializer () );
    Gson gson = gsonBuilder.create();




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2