2

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.

John Humphreys
  • 37,047
  • 37
  • 155
  • 255
  • Do the objects have attributes, some of which have child nodes you have to recurse into? When I've had to format data like this a simple recursive enumeration that has an indentation parameter that gets incremented at each level of recursion has always come in handy. – David Conrad Apr 07 '14 at 18:15
  • Yeah, they have attributes. I was thinking along the same lines as you... Maybe like a "toString(int tabs)" function that I can call for each entity, and I just return the tabs + the normal toString() for the entity. I was kinda hoping there's a library that prints out the attributes of each class though to avoid the extra code. – John Humphreys Apr 07 '14 at 19:35
  • Well, I don't know of one. Maybe someone else will reply with one. – David Conrad Apr 07 '14 at 20:03

1 Answers1

1

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"
   }
]
}
Per Lundberg
  • 3,837
  • 1
  • 36
  • 46