json数据格式用于数据传输转换是十分方便的,但是直接预览的可读性差,所以把json串转换为html串,可以直接在页面展示。
这种html展示在json列表中效果尤为明显。
注意:json格式一定要正确! 文件再大也不能分页!
public class Json2Html {
private static String html = "";
/**
* 将json格式字符串转换成html字符串
* @param json String
* @return html String
*/
public static String jsonToHtml(String json) {
//判断json格式是否规范
if (isGoodJson(json)) {
JsonElement j = new JsonParser().parse(json);
html = "";
json2html(j);
return html;
} else {
return "json数据格式不规范,无法解析。"+json;
}
}
/**
* 判断json串格式是否规范
* @param json String
* @return true(规范) false(不规范)
*/
public static boolean isGoodJson(String json) {
if (StringUtils.isBlank(json)) {
return false;
}
try {
new JsonParser().parse(json);
return true;
} catch (JsonParseException e) {
//System.out.println("bad json: " + json);
return false;
}
}
/**
* json转html (递归)
* @param json gson对象
* 转换过程不断修改全局html String
*/
public static void json2html(JsonElement json){
//数组 绘制表格
if(json.isJsonArray()){
JsonArray jArray = json.getAsJsonArray();
Iterator it = jArray.iterator();
html += "
int f = 0;
while(it.hasNext()){
JsonElement jsonElement=(JsonElement) it.next();
if(f == 0){
html += "";
jsonGetHead(jsonElement);
html += "
";}
html += "
";jsonGetBody(jsonElement);
html += "
";f++;
}
html += "
";html += "
";}else
//对象 (map)
if(json.isJsonObject()){
JsonObject jObject = json.getAsJsonObject();
Set> entrySet = jObject.entrySet();
Iterator> iter = entrySet.iterator();
while(iter.hasNext()){
// htmlBegin += "
";// htmlEnd = "
" + htmlEnd;Entry entry = iter.next();
String key = entry.getKey();
html += key;
html += "=";
JsonElement value = entry.getValue();
json2html(value);
}
}else
//单一字符
if(json.isJsonPrimitive()){
String finals = json.getAsString();
html += finals;
}else if(json.isJsonNull()){
}
}
/**
* 数组绘制表格 添加表头
* @param json
*/
private static void jsonGetHead(JsonElement json){
JsonObject jObject = json.getAsJsonObject();
Set> entrySet = jObject.entrySet();
Iterator> iter = entrySet.iterator();
while(iter.hasNext()){
Entry entry = iter.next();
String key = entry.getKey();
html += "
" + key + "";}
}
/**
* 数组绘制表格 添加表体
* @param json
*/
private static void jsonGetBody(JsonElement json){
JsonObject jObject = json.getAsJsonObject();
Set> entrySet = jObject.entrySet();
Iterator> iter = entrySet.iterator();
while(iter.hasNext()){
Entry entry = iter.next();
html += "
";JsonElement value = entry.getValue();
json2html(value);
html += "
";}
}
}
遗憾的是,文件达到20M左右程序就基本瘫痪了。如何解?