use of com.gpcoder.gson.object.AmazonBook in project Java-Tutorial by gpcodervn.
the class JsonAdapterExample method main.
public static void main(String[] args) {
final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(AmazonBook.class, new CustomTypeAdapter());
gsonBuilder.setPrettyPrinting();
final Gson gson = gsonBuilder.create();
final AmazonBook book = new AmazonBook();
book.setTitle("Head First Design Patterns");
book.setIsbn10("0596007124");
book.setIsbn13("978-0596007126");
book.setPrice(52.41);
Calendar c = Calendar.getInstance();
c.set(2004, Calendar.OCTOBER, 1);
book.setPublishedDate(c.getTime());
String[] authors = new String[] { "Eric Freeman", "Bert Bates", "Kathy Sierra", "Elisabeth Robson" };
book.setAuthors(authors);
System.out.println("Convert Book object to JSON string: ");
final String json = gson.toJson(book);
System.out.println(json);
System.out.println("Convert JSON String to Book object: ");
final AmazonBook parsedBook1 = gson.fromJson(json, AmazonBook.class);
System.out.println(parsedBook1);
}
use of com.gpcoder.gson.object.AmazonBook in project Java-Tutorial by gpcodervn.
the class CustomTypeAdapter method read.
@Override
public AmazonBook read(final JsonReader in) throws IOException {
final AmazonBook book = new AmazonBook();
in.beginObject();
while (in.hasNext()) {
switch(in.nextName()) {
case "title":
book.setTitle(in.nextString());
break;
case "isbn-10":
book.setIsbn10(in.nextString());
break;
case "isbn-13":
book.setIsbn13(in.nextString());
break;
case "price":
book.setPrice(in.nextDouble());
break;
case "publishedDate":
Date publishedDate = null;
try {
publishedDate = sdf.parse(in.nextString());
} catch (ParseException e) {
e.printStackTrace();
}
book.setPublishedDate(publishedDate);
break;
case "authors":
in.beginArray();
final List<String> authors = new ArrayList<>();
while (in.hasNext()) {
authors.add(in.nextString());
}
in.endArray();
book.setAuthors(authors.toArray(new String[authors.size()]));
break;
}
}
in.endObject();
return book;
}
Aggregations