I've never attempted to parse JSON before. I have some books in a JSON format like this:
{
"Search": {
"Books": [
{
"isbn": "1849830347",
"title": "American Assassin",
"author": "Vince Flynn",
"price": 7.99
},
{
"isbn": "0857208683",
"title": Kill Shot",
"author": "Vince Flynn",
"price": 5.99
},
...
}
}
What I want is to parse them and end up with a List of populated Book objects. I have played around with Jackson and with Google's GSON. I finally got this to work but I'm not really happy with it. This is just code that works, what I want my solution to be is good code for when I work with JSON again in the future - I imagine this is inefficient because I'm first turning it into a tree and then parsing that. Can anyone suggest improvements?
List<Book> books = new ArrayList<Book>();
JsonFactory f = new JsonFactory();
JsonParser jp = f.createJsonParser(json);
jp.setCodec(new ObjectMapper());
JsonNode node = jp.readValueAsTree();
JsonNode books = node.findValue("Books");
Iterator<JsonNode> it = books.getElements();
while(it.hasNext()){
JsonNode temp = it.next();
Book book = new Book();
book.setIsbn(temp.findValue("isbn").asText());
book.setTitle(temp.findValue("title").asText());
book.setAuthor(temp.findValue("author").asText());
book.setPrice(temp.findValue("price").asDouble());
books.add(book);
}
The only reason I have the setCodec line is because without it, I was getting an IllegalStateException with the message: No ObjectCodec defined for the parser, can not deserialize JSON into JsonNode tree.
From Jackson API, I had tried using the Streaming API method. But I had to call jp.nextToken() about 10 times just to get to the first isbn value and it looked very messy. Although the API does say its 20% / 30% faster.
Appreciate any feedback on this.