要使其“正确”,您可以使用类似的东西
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;
}
}
然后使用它:
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));
}
}
希望这有助于某人:-)