3

How to convert a json object into HTML in java?

3 Answers 3

5

This code displays any Json object to HTML (using org.json lib):

/**
 * Get the JSON data formated in HTML
 */ 
public String getHtmlData( String strJsonData ) {
    return jsonToHtml( new JSONObject( strJsonData ) );
}

/**
 * convert json Data to structured Html text
 * 
 * @param json
 * @return string
 */
private String jsonToHtml( Object obj ) {
    StringBuilder html = new StringBuilder( );

    try {
        if (obj instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject)obj;
            String[] keys = JSONObject.getNames( jsonObject );

            html.append("<div class=\"json_object\">");

            if (keys.length > 0) {
                for (String key : keys) {
                    // print the key and open a DIV
                    html.append("<div><span class=\"json_key\">")
                        .append(key).append("</span> : ");

                    Object val = jsonObject.get(key);
                    // recursive call
                    html.append( jsonToHtml( val ) );
                    // close the div
                    html.append("</div>");
                }
            }

            html.append("</div>");

        } else if (obj instanceof JSONArray) {
            JSONArray array = (JSONArray)obj;
            for ( int i=0; i < array.length( ); i++) {
                // recursive call
                html.append( jsonToHtml( array.get(i) ) );                    
            }
        } else {
            // print the value
            html.append( obj );
        }                
    } catch (JSONException e) { return e.getLocalizedMessage( ) ; }

    return html.toString( );
}

then you just need to add specific CSS, like :

.json_object { margin:10px; padding-left:10px; border-left:1px solid #ccc}
.json_key { font-weight: bold; }
Sign up to request clarification or add additional context in comments.

1 Comment

For JSONObject which library we have to include?
4

There's no automatic way because a JSON object contains only data while in HTML there's markup semantics (there's no 1:1 mapping between JSON and HTML).

Comments

0

In trying to find an answer to your question, for myself, I came across this: Jemplate Not sure if that will help you. It did help me.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.