Perl Data::Dumper for Java
Programming Estimated reading time: ~1 minutes
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));</span>
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.
A note about Netcup (advertisement)
Netcup is a German hosting company. Netcup offers inexpensive, yet powerfull web hosting packages, KVM-based root servers or dedicated servers for example. Using a coupon code from my Netcup coupon code web app you can even save more money (6$ on your first purchase, 30% off any KVM-based root server, ...).