javaloggingioobject-graph

Pretty-print object hierarchy in Java?


I'm working on a data analytics project where we are representing a lot of the basic entities you find in a language. I'd like to find a better way to print out their object graphs though for debugging purposes though. So, for example, we might have:

Function: Average
Description: some description
Overload #1:
    parameter-set: paramset-a
        columns: 
           currency: string
           value: double
           scale: integer
    result-set: result-set-a
    preference: first-find
Overload #2: ...
Overload #3: ...

My Question

Let's say, in the above example, Function is my root object. Function has some attributes and a series of overloads, each with their own attributes and child objects.

Is there a library that can help me to print the object graph under a root function, in a well-formatted way?

PS: The above example is relatively trivial; in many of our cases, the object hierarchies are 6-10 levels deep, and that's when the real problem comes in.


Solution

  • This is far from perfect, but this question really deserves an answer.

    https://github.com/EsotericSoftware/jsonbeans is one way to kind of accomplish something like this. It converts arbitrary Java objects (without having to annotate the fields or anything) to JSON, and includes a pretty-printing method. It can do approximately what you are asking for.

    Using this library, you can do something like this:

    Json json = new Json();
    System.out.println(json.prettyPrint(person));
    

    For some example data, the output you might get looks like this:

    {
    "name": "Nate",
    "age": 31,
    "numbers": [
       {
          "name": "Home",
          "class": "com.example.PhoneNumber",
          "number": "206-555-1234"
       },
       {
          "name": "Work",
          "class": "com.example.PhoneNumber",
          "number": "425-555-4321"
       }
    ]
    }