java - Custom deserialization of enum using GSON -
i need make 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 simplified example, filestructureelement
class has many more properties, irrelevant question fields.
i want load values of contenttype
property values of elementtype
. can not afford making values of enum match types of json, because 1 of possible values in json "default", not valid enum value. furthermore, not have enum values lowercase names. means need customization of gson parsing. can me that?
the idea here (checking values of property parse , choosing upon whether load enum value or not), not me because have no control of web service interface talk , values obvious , risk present values of of other json atttributes.
if want custom parsing enum, need register 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 right enum value provided string.
Comments
Post a Comment