Friday 3 August 2012

Parse & Create JSON Documents in Java

The Jackson JSON library provides means to process and create JSON files à la DOM and StAX. It is also possible to process plain old java objects (POJO's). The code samples described here are available at GitHub.

DOM

The following code loads a JSON into a tree structure, then extracts contents by retrieving elements manually:
  String json = "{\"Id\":123456," +
    "\"Title\":\"My book title\"," +
    "\"References\":[\"Reference A\",\"Reference B\"]}";

  System.out.println("Source: " + json);

  // Parsing JSON into tree structure
  ObjectMapper om = new ObjectMapper();
  JsonNode retr = om.readTree(json);

  // Retrieving items from the structure
  JsonNode id_node = retr.get("Id");
  System.out.println("Id" + id_node.asInt());

  JsonNode id_title = retr.get("Title");
  System.out.println("Title " + id_title.asText());

  JsonNode id_refs = retr.get("References");
  System.out.print("References ");

  // Retrieving sub-elements
  Iterator<JsonNode> it = id_refs.elements();

  while ( it.hasNext() ) {
    System.out.print(" " + it.next().asText());
  }

  System.out.println(" ");
The above produces the following:
Source: {"Id":123456,"Title":"My book title","References":["Reference A","Reference B"]}
Id 123456
Title My book title
References Reference A Reference B

StAX

The code below performs a round trip, that is, the manual creation of a JSON and manual parsing with tokens:
JsonFactory jf = new JsonFactory();

// Creating in memory representation
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JsonGenerator jg = jf.createJsonGenerator(
  baos, JsonEncoding.UTF8);

jg.writeStartObject();

jg.writeNumberField("Id", 123456);
jg.writeStringField("Title", "My book title");
jg.writeFieldName("References");

jg.writeStartArray();
jg.writeString("Reference A");
jg.writeString("Reference B");
jg.writeEndArray();

jg.writeEndObject();
jg.close();

// Printing JSON
String result = baos.toString("UTF8");
System.out.println(result);

// Parsing JSON
JsonParser jp = jf.createJsonParser(result);

while (jp.nextToken() != JsonToken.END_OBJECT) {
  String token = jp.getCurrentName();
  if ( "Id".equals(token) || "Title".equals(token) ) {
    System.out.print(token + " ");
    jp.nextToken();
    System.out.println(jp.getText());
  } else if ( "References".equals(token) ) {
    System.out.print(token + " ");
    jp.nextToken(); // JsonToken.START_ARRAY
    while (jp.nextToken() != JsonToken.END_ARRAY) {
      System.out.print(jp.getText() + " ");
    }
    System.out.println("");
  }
}

jp.close();
The produced output is:
{"Id":123456,"Title":"My book title","References":["Reference A","Reference B"]}
Id 123456
Title My book title
References Reference A Reference B

POJO

This example uses a plain old Java object (POJO):
public class PojoItem {

  private int id = 123456;
  private String title;
  private List<String> references
    = new ArrayList<String>() {{
        add("Reference A"); add("Reference B"); }
      };

  public int getId() { 
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getTitle() {
    return title;
  }

  public void setTitle(String title) {
    this.title = title;
  }

  public List<String> getReferences() {
    return references;
  }

  public void setReferences(List<String> references) {
    this.references = references;
  }

}
The following transform a POJO into an JSON, and then back into a POJO instance:
PojoItem pi = new PojoItem();
pi.setId(123466);
pi.setTitle("My Title");
pi.setReferences(new ArrayList<String>() { {
  add("Reference A"); add("Reference B");
} });

// Creating and printing JSON
ObjectMapper om = new ObjectMapper();
String result = om.writeValueAsString(pi);
System.out.println(result);

// Parsing JSON
PojoItem user = om.readValue(result, PojoItem.class);

System.out.println("id " + user.getId());
System.out.println("title " + user.getTitle());
System.out.print("references ");
for (String s : user.getReferences()) {
  System.out.print(s + " ");
}

System.out.println(" ");
The above code creates a JSON from a plain old Java object. The output is:
{"id":123466,"title":"My Title","references":["Reference A","Reference B"]}
id 123466
title My Title
references Reference A Reference B

Pojo to XMLPojo to JSONJAXB to XMLJAXB to JSONJAXB Crash Course

No comments:

Post a Comment