开发者

How to convert a json object into HTML format in java?

开发者 https://www.devze.com 2023-01-14 00:54 出处:网络
How to convert a json object into HTML in ja开发者_JS百科va?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

How to convert a json object into HTML in ja开发者_JS百科va?


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


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; }


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.

0

精彩评论

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