I have been working on a Cloud Dataflow project that parses incoming App Engine logs to generate status statistics such as numer of errors in the last 10 minutes. The incoming data is a JSON representation of a LogEntry object. A LogEntry object is represented in Java as a LogEntry class. The task I found myself in was converting the JSON representation of a LogEntry into the Java object for downstream processing.

For solving this problem, I dug into the Google HTTP Client Library for Java and found a method for converting from JSON to any abritrary Java object. The client library contains custom parsers that understand the common serialization format the Google uses to convert an object to JSON. By using those parsers I was able to easily deserialize JSON into a useable Java object. The following code snippet shows how it was done. This method is not limited to LogEntry objects and can convert any JSON object into a corresponding object from Google’s client libraries.

package com.sookocheff;

import java.io.IOException;

import com.google.api.client.json.JsonParser;
import com.google.api.client.json.jackson2.JacksonFactory;

import com.google.api.services.logging.model.LogEntry;

public class App
{

  public static void main( String[] args )
  {
    final String json = "..."; // A LogEntry JSON representation
    JacksonFactory factory = new JacksonFactory();
    try {
      JsonParser jp = factory.createJsonParser(json);
      LogEntry entry = jp.parse(LogEntry.class);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}