, Gson JSON . Gson , , - , . , , , , , .
, , :
public class Person {
private String name;
private int age;
private Person parent = null;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
Person joe = new Person("Joe", 20);
Gson gson = new Gson();
String json = gson.toJson(joe);
==> json is {"name":"Joe","age":"20"}
, , . , , , , .
Person joe = gson.fromJson(json, Person.class);
- , , . :
- , . (DateTime ..). Gson . : Json Serialiers: Json Deserializers: Instance Creators: no-args
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());
The registerTypeAdapter call checks to see if an adapter of type implements more than one of these interfaces and register it for all of them.
Writing a serializer
Here is an example of how to write a custom serializer for the JodaTime DateTime class.
private class DateTimeSerializer implements JsonSerializer<DateTime> {
public JsonElement serialize(DateTime src, Type typeOfSrc,
JsonSerializationContext context) {
return new JsonPrimitive(src.toString());
}
}
Gson calls toJson () when it launches a DateTime object during serialization.
Writing a Deserializer
Here is an example of how to write a custom deserializer for the JodaTime DateTime class.
private class DateTimeDeserializer implements
JsonDeserializer<DateTime> {
public DateTime deserialize(JsonElement
json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
return new DateTime(json.getAsJsonPrimitive().getAsString());
}
}
Gson calls fromJson () when it needs to deserialize a fragment of a JSON string into a DateTime object