How to serialize enums to ints instead of strings with Gson?
(Below answer is from chatGPT)
By default, the Gson library serializes enums into strings. However, if you want to serialize enums into integers instead of strings, you can create a custom Gson serializer/deserializer for your enum class. Here’s an example of how you can achieve this:
1.
public enum MyEnum {
VALUE1 ( 1 ),
VALUE2 ( 2 ),
VALUE3 ( 3 );
private int value ;
MyEnum ( int value ) {
this . value = value ;
}
public int getValue () {
return value ;
}
}
2.
import com.google.gson.* ;
public class MyEnumSerializer implements JsonSerializer < MyEnum >, JsonDeserializer < MyEnum > {
@Override
public JsonElement serialize ( MyEnum myEnum , Type typeOfSrc , JsonSerializationContext context ) {
return new JsonPrimitive ( myEnum . getValue ());
}
@Override
public MyEnum deserialize ( JsonElement json , Type typeOfT , JsonDeserializationContext context )
throws JsonParseException {
int value = json . getAsInt ();
for ( MyEnum myEnum : MyEnum . values ()) {
if ( myEnum . getValue () == value ) {
return myEnum ;
}
}
throw new JsonParseException ( "Invalid enum value: " + value );
}
}
3.
import com.google.gson.Gson ;
import com.google.gson.GsonBuilder ;
public class Main {
public static void main ( String [] args ) {
GsonBuilder gsonBuilder = new GsonBuilder ();
gsonBuilder . registerTypeAdapter ( MyEnum . class , new MyEnumSerializer ());
Gson gson = gsonBuilder . create ();
// Serialize
String json = gson . toJson ( MyEnum . VALUE1 );
System . out . println ( json ); // Output: 1
// Deserialize
MyEnum myEnum = gson . fromJson ( "2" , MyEnum . class );
System . out . println ( myEnum ); // Output: VALUE2
}
}