GSON. workaround for enum and int
From kjones' answer, here's a Kotlin translation:
enum class ObjectTypeEnum(val value:Int) {
@SerializedName("0")
UNKNOWN_TYPE(0),
@SerializedName("11")
SIMPLE_TYPE(11),
@SerializedName("42")
COMPLEX_TYPE(42)
}
Or, without needing the Int values:
enum class ObjectTypeEnum {
@SerializedName("0")
UNKNOWN_TYPE,
@SerializedName("11")
SIMPLE_TYPE,
@SerializedName("42")
COMPLEX_TYPE
}
You can just use the @SerializedName annotation to determine what value gets serialized to/from the wire. Then you don't need to write a custom TypeAdapter.
import com.google.gson.annotations.SerializedName;
public enum ObjectTypeEnum {
@SerializedName("0")
UNKNOWN_TYPE(0),
@SerializedName("11")
SIMPLE_TYPE(11),
@SerialziedName("42")
COMPLEX_TYPE(42);
private int value;
private ObjectTypeEnum(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
If you don't have a need for getting the wire value in your code you can eliminate the "value" field and related code.
public enum ObjectTypeEnum {
@SerializedName("0")
UNKNOWN_TYPE,
@SerializedName("11")
SIMPLE_TYPE,
@SerialziedName("42")
COMPLEX_TYPE;
}
Using an answer from Chin and help from my workmate I get following solution.
I wrote an inner class in the parser class.
private static class ObjectTypeDeserializer implements
JsonDeserializer<ObjectTypeEnum>
{
@Override
public PreconditioningStatusEnum deserialize(JsonElement json,
Type typeOfT, JsonDeserializationContext ctx)
throws JsonParseException
{
int typeInt = json.getAsInt();
return ObjectTypeEnum
.findByAbbr(typeInt);
}
}
and created GSON-Object on following way:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(ObjectTypeEnum.class, new ObjectTypeDeserializer() );
Gson gson = gsonBuilder.create();
http://sites.google.com/site/gson/gson-user-guide#TOC-Custom-Serialization-and-Deserializ