如何在java中将json对象转换为HTML?
答案 0 :(得分:3)
没有自动方式,因为JSON对象只包含数据,而在HTML中则有标记语义(JSON和HTML之间没有1:1的映射)。
答案 1 :(得分:0)
在尝试找到问题的答案时,对于我自己,我遇到了这个问题:Jemplate不确定这是否会对您有所帮助。它确实帮助了我。
答案 2 :(得分:0)
此代码将任何Json对象显示为HTML(使用org.json lib):
string searchFilter = "(objectclass=*)";//string.Empty;
string searchBase = "OU=Users,OU=TOD,OU=Departments,DC=domain,DC=com";
LdapSearchConstraints constraints = new LdapSearchConstraints
{
TimeLimit = 15000
};
#region connection information
string host = "dm1.domain.com";
string un = "domain\\doatemp2";
string pass = "password";
int port = 389;
#endregion
try
{
using (var conn = new LdapConnection { SecureSocketLayer = false })
{
conn.Connect(host, port);
conn.Bind(un, pass);
LdapSearchResults searchResults = conn.Search(
searchBase,
LdapConnection.SCOPE_SUB,
searchFilter,
null, // no specified attributes
false, // return attr and value
constraints);
while (searchResults.hasMore())
{
count++;
var nextEntry = searchResults.next(); // hits and then goes to timeout
nextEntry.getAttributeSet();
Console.WriteLine("Distinguished Name:" + nextEntry.getAttribute("distinguishedName").StringValue);
Console.ReadKey();
}
}
}
catch (LdapException ldapEx)
{
Console.WriteLine(ldapEx.ToString()); // ocassional time outs
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
foreach(var u in users)
{
Console.WriteLine("Key:" + u.Key.ToString() + " | Value:" + u.Value.ToString());
}
Console.ReadKey();
}
然后你只需要添加特定的CSS,例如:
/**
* 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( );
}