简体   繁体   中英

Custom deserialization of enum using GSON

I need to make the following json:

[ { "contentType": "folder" },
  { "contentType": "image" },
  { "contentType": "video" }
]

Parse in such array:

FileStructureElement [] elements[];

Having:

public class FileStructureElement {
    private ElementType contentType;
}

public enum ElementType {
    FOLDER, IMAGE, VIDEO, DEFAULT;
}

This is simplified example, FileStructureElement class has many more properties, irrelevant for the question fields.

I want to load the values of contentType property as values of ElementType . I can not afford making the values of the enum match the types of the json, because one of the possible values in the json is "default", which is not a valid enum value. Furthermore, I would like to not have enum values with lowercase names. This basically means I need customization of the GSON parsing. Can somebody help me with that?

The idea from here (checking the values of the property i parse and choosing upon it whether to load enum value or not), does not help me because I have no control of the web service interface I talk to and the values are too obvious and I risk that they will also be present as values of some of the other json atttributes.

If you want a custom parsing for the enum, you need to register an adapter

JsonDeserializer<?> jd = new JsonDeserializer<ElementType>() {
  @Override
  public ElementType deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    String enumStr = json.getAsString();
    ElementType val = 
    //...

    return val;
  }
};

Gson gson = new GsonBuilder().registerTypeAdapter(ElementType.class, jd).create();

Just return the right enum value for the provided String.

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