2

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.

Community
  • 1
  • 1
Boris Strandjev
  • 46,145
  • 15
  • 108
  • 135

1 Answers1

4

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.

PomPom
  • 1,468
  • 11
  • 20