开发者

Convert any object to pretty HTML in java

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.


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


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.


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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜