By default, all fields of an object will be serialized/deserialized.
Google Gson provides useful annotations which can customize the serialization/deserialization of object to/from JSON.
Examples:
class Card {
@SerializedName("_id")
long id;
@Expose
int field1;
@Expose (serialize = false, deserialize = false)
Drawable thumb;
String[] tags=[];
}
annotation
description
Expose
Indicates how this member should be exposed for JSON serialization or deserialization.
JsonAdapter
Specifies the Gson TypeAdapter for a class or field.
SerializedName
Specifies the JSON name of field.
Since
Indicates the version number since a member or a type has been present.
Until
Indicates the version number until a member or a type should be present.
custom serialization and deserialization
By default Gson converts application classes to JSON using its built-in type adapters. Gson allows to provide a custom adapters for
JSON serializers - custom serialization for an object
JSON deserializers - custom deserialization for a type
instance creators - not needed if no-args constructor is available or a deserializer is registered
type adapters - if Gson's default JSON conversion isn't appropriate for a type, extend the TypeAdapter class to customize the conversion.
Examples:
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(MyType2.class, new MyTypeAdapter());
gson.registerTypeAdapter(MyType.class, new MySerializer());
gson.registerTypeAdapter(MyType.class, new MyDeserializer());
gson.registerTypeAdapter(MyType.class, new MyInstanceCreator());private class DateTimeSerializer implements JsonSerializer<DateTime> {
public JsonElement serialize(DateTime src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.toString());
}
}private class DateTimeDeserializer implements JsonDeserializer<DateTime> {
public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
return new DateTime(json.getAsJsonPrimitive().getAsString());
}
}private class MoneyInstanceCreator implements InstanceCreator<Money> {
public Money createInstance(Type type) {
return new Money("1000000", CurrencyCode.USD);
}
}
class MyList<T> extends ArrayList<T> {
}
class MyListInstanceCreator implements InstanceCreator<MyList<?>> {
@SuppressWarnings("unchecked")
public MyList<?> createInstance(Type type) {
// No need to use a parameterized list since the actual instance will have the raw type anyway.
return new MyList();
}
}