Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GSON Serialize boolean to 0 or 1

Tags:

All,

I'm trying to do the following:

public class SomClass {     public boolean x;     public int y;     public String z; }         SomClass s = new SomClass(); s.x = true; s.y = 10; s.z = "ZZZ"; Gson gson = new Gson(); String retVal = gson.toJson(s); return retVal; 

So this little snippet will produce:

{"x":true,"y":10,"z":"ZZZ"} 

but what I need it to produce is:

{"x":0, "y":10,"z":"ZZZ"} 

Can someone please give me some options? I'd prefer not to rewrite my booleans as ints as that will cause several issues with existing code (nonobvious, hard to read, hard to enforce, etc.)

like image 752
Austin Avatar asked Mar 07 '12 18:03

Austin


2 Answers

To make it "correct" way, you can use something like that

import java.lang.reflect.Type;  import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer;  public class BooleanSerializer implements JsonSerializer<Boolean>, JsonDeserializer<Boolean> {      @Override     public JsonElement serialize(Boolean arg0, Type arg1, JsonSerializationContext arg2) {         return new JsonPrimitive(Boolean.TRUE.equals(arg0));     }      @Override     public Boolean deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {         return arg0.getAsInt() == 1;     } } 

And then use it:

public class Main {      public class Base {         @Expose         @SerializedName("class")         protected String clazz = getClass().getSimpleName();         protected String control = "ctrl";     }      public class Child extends Base {         protected String text = "This is text";         protected Boolean boolTest = false;     }      /**      * @param args      */     public static void main(String[] args) {         Main m = new Main();         GsonBuilder b = new GsonBuilder();         BooleanSerializer serializer = new BooleanSerializer();         b.registerTypeAdapter(Boolean.class, serializer);         b.registerTypeAdapter(boolean.class, serializer);         Gson gson = b.create();          Child c = m.new Child();         System.out.println(gson.toJson(c));         String testStr = "{\"text\":\"This is text\",\"boolTest\":1,\"class\":\"Child\",\"control\":\"ctrl\"}";         Child cc = gson.fromJson(testStr, Main.Child.class);         System.out.println(gson.toJson(cc));     } } 

Hope this helps someone :-)

like image 120
Damian Walczak Avatar answered Sep 20 '22 18:09

Damian Walczak


or this: Gson User Guide - Custom Serialization and Deserialization

like image 43
GreyBeardedGeek Avatar answered Sep 19 '22 18:09

GreyBeardedGeek