Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert any object to pretty HTML in java

Tags:

java

html

How can I convert a given object (in a generic way with reflection) to pretty printable HTML? What ready made library do you recommend that does this? I need support for simple nested objects (as long as they don't create loops in the object graph).

I tried to convert it to JSON, but DefaultPrettyPrinter is not HTML friendly.

like image 474
ripper234 Avatar asked May 24 '10 07:05

ripper234


3 Answers

You could create an XSLT style for the XML output of xstream on your object.

like image 92
cherouvim Avatar answered Nov 13 '22 23:11

cherouvim


You could relatively easily write your own library for doing so. Here's some example code that you could modify relatively easily to show html. Another option is to display the JSON inside a code tag in html. One final option is to use ReflectionToStringBuilder in apache commons lang and again show the result inside of a code tag in html. Using apache commons is probably no better than the json format however.

like image 4
Jay Askren Avatar answered Nov 14 '22 00:11

Jay Askren


Can be done in a two step process:

  1. Convert object to JSON using any library of your preference, e.g. jackson:
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);
  1. Convert JSON string to HTML using a ready-made solution, such as json2html or write your own implementation. Have a look at the visualizer demo. You can also use the open-source jsoneditor which has an ad-supported online version.
like image 1
ccpizza Avatar answered Nov 13 '22 22:11

ccpizza