使用反序列化程序。像这样:
public class BookDeserializer implements JsonDeserializer<Book> {
@Override
public Book deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
throws JsonParseException {
final JsonObject jsonObject = json.getAsJsonObject();
final String title = jsonObject.get("title").getAsString();
JsonElement metaElement = jsonObject.get("metadata");
final String author = metaElement.get("author").getAsString();
final Book book = new Book();
book.setTitle(title);
book.setAuthor(author);
return book;
}
}
如何使用:
sGson = new GsonBuilder()
.registerTypeAdapter(Book.class, new BookDeserializer())
.create();