java中如何将json对象转换为HTML格式?

sel*_*lva 3 html java json

如何在java中将json对象转换为HTML?

seb*_*boo 5

此代码将任何 Json 对象显示为 HTML(使用 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( );
}
Run Code Online (Sandbox Code Playgroud)

那么你只需要添加特定的 CSS,例如:

.json_object { margin:10px; padding-left:10px; border-left:1px solid #ccc}
.json_key { font-weight: bold; }
Run Code Online (Sandbox Code Playgroud)