Thursday, November 26, 2015

Perl Data::Dumper for Java

In Perl, if you want to display the contents of a data structure in a human readable format you can use the great Data::Dumper module. In PHP there is the var_dump() function. But what to do in Java? You can use the XStream library:

"XStream uses reflection to discover the structure of the object graph to serialize at run time, and doesn't require modifications to objects. It can serialize internal fields, including private and final, and supports non-public and inner classes." - Wikipedia

If you use Maven to manage your depedencies just add the following artifact to you POM:

<dependency>
    <groupid>com.thoughtworks.xstream</groupid>
    <artifactid>xstream</artifactid>
    <version>1.4.8</version>
</dependency>

The XStream library can be used as follows to print the contents of an arbitrary data structure nicely formatted to the console.

XStream dumper = new XStream(new JsonHierarchicalStreamDriver());
System.out.println(dumper.toXML(lockMap));

The output:

{"map": [
  [
    {
      "longitude": 110649,
      "latitute": 107551,
      "outer-class": {}
    },
    [
      {
        "unixTimestamp": 1448570378 ,
        "temperature": 10.87,
        "outer-class": {
          "@reference": "../../../com.example.CoordinateRepository$CoordinateKey/outer-class"
        }
      },
      {
        "unixTimestamp": 1448570409,
        "temperature": 10.89,
        "outer-class": {
          "@reference": "../../../com.example.CoordinateRepository$CoordinateKey/outer-class"
        }
      }
    ]
  ]
]}

If you know any other libraries, approaches or solutions for this problem just let me know by dropping a comment below or sending me an email. I will update this post accordingly.

No comments:

Post a Comment