100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > json 转换成html json字符串转换为html字符串

json 转换成html json字符串转换为html字符串

时间:2021-10-22 02:06:58

相关推荐

json 转换成html json字符串转换为html字符串

json数据格式用于数据传输转换是十分方便的,但是直接预览的可读性差,所以把json串转换为html串,可以直接在页面展示。

这种html展示在json列表中效果尤为明显。

注意:json格式一定要正确! 文件再大也不能分页!

publicclassJson2Html{

privatestaticStringhtml="";

/**

*将json格式字符串转换成html字符串

*@paramjsonString

*@returnhtmlString

*/

publicstaticStringjsonToHtml(Stringjson){

//判断json格式是否规范

if(isGoodJson(json)){

JsonElementj=newJsonParser().parse(json);

html="";

json2html(j);

returnhtml;

}else{

return"json数据格式不规范,无法解析。"+json;

}

}

/**

*判断json串格式是否规范

*@paramjsonString

*@returntrue(规范)false(不规范)

*/

publicstaticbooleanisGoodJson(Stringjson){

if(StringUtils.isBlank(json)){

returnfalse;

}

try{

newJsonParser().parse(json);

returntrue;

}catch(JsonParseExceptione){

//System.out.println("badjson:"+json);

returnfalse;

}

}

/**

*json转html(递归)

*@paramjsongson对象

*转换过程不断修改全局htmlString

*/

publicstaticvoidjson2html(JsonElementjson){

//数组绘制表格

if(json.isJsonArray()){

JsonArrayjArray=json.getAsJsonArray();

Iteratorit=jArray.iterator();

html+="

intf=0;

while(it.hasNext()){

JsonElementjsonElement=(JsonElement)it.next();

if(f==0){

html+="";

jsonGetHead(jsonElement);

html+="

";

}

html+="

";

jsonGetBody(jsonElement);

html+="

";

f++;

}

html+="

";

html+="

";

}else

//对象(map)

if(json.isJsonObject()){

JsonObjectjObject=json.getAsJsonObject();

Set>entrySet=jObject.entrySet();

Iterator>iter=entrySet.iterator();

while(iter.hasNext()){

//htmlBegin+="

";

//htmlEnd="

"+htmlEnd;

Entryentry=iter.next();

Stringkey=entry.getKey();

html+=key;

html+="=";

JsonElementvalue=entry.getValue();

json2html(value);

}

}else

//单一字符

if(json.isJsonPrimitive()){

Stringfinals=json.getAsString();

html+=finals;

}elseif(json.isJsonNull()){

}

}

/**

*数组绘制表格添加表头

*@paramjson

*/

privatestaticvoidjsonGetHead(JsonElementjson){

JsonObjectjObject=json.getAsJsonObject();

Set>entrySet=jObject.entrySet();

Iterator>iter=entrySet.iterator();

while(iter.hasNext()){

Entryentry=iter.next();

Stringkey=entry.getKey();

html+="

"+key+"";

}

}

/**

*数组绘制表格添加表体

*@paramjson

*/

privatestaticvoidjsonGetBody(JsonElementjson){

JsonObjectjObject=json.getAsJsonObject();

Set>entrySet=jObject.entrySet();

Iterator>iter=entrySet.iterator();

while(iter.hasNext()){

Entryentry=iter.next();

html+="

";

JsonElementvalue=entry.getValue();

json2html(value);

html+="

";

}

}

}

遗憾的是,文件达到20M左右程序就基本瘫痪了。如何解?

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。