控制台输出json字符串:
{"header":{"transSn":"e33128bb7622462ebfb2cbfcc46baa14","dateTime":"1002110000","serviceCode":"********","appId":"999999999999","bizId":"000000","version":"1.0","resType":"A","resCode":"SSS000","resMsg":"交易成功(业务附加消息:*****)"},"resBody":{"operator":"lgh","rowNumStart":"1","pageRowNum":"100","pageFlag":"0","totalRowNum":"1","orderFlag":"0","orderField":"","result":[{"flag":"1","riskCode":"00567000","riskName":"567*********","prem":"520.00","amntOrMult":"***","amnt":"200000","polNo":"12177"}]}}
在Java后台如何进行json格式化输出呢下面直接贴代码。
封装一个工具类专门转换json格式化:
*@param resString* @returnString* @throws
*@Description 响应数据格式化*@author lgh* @date /10/29-13:45
*/
privateString responseFormat(String resString){
StringBuffer jsonForMatStr= newStringBuffer();int level = 0;for(int index=0;index
{//获取s中的每个字符
char c =resString.charAt(index);//level大于0并且jsonForMatStr中的最后一个字符为\n,jsonForMatStr加入\t
if (level > 0 && '\n' == jsonForMatStr.charAt(jsonForMatStr.length() - 1)) {
jsonForMatStr.append(getLevelStr(level));
}//遇到"{"和"["要增加空格和换行,遇到"}"和"]"要减少空格,以对应,遇到","要换行
switch(c) {case '{':case '[':
jsonForMatStr.append(c+ "\n");
level++;break;case ',':
jsonForMatStr.append(c+ "\n");break;case '}':case ']':
jsonForMatStr.append("\n");
level--;
jsonForMatStr.append(getLevelStr(level));
jsonForMatStr.append(c);break;default:
jsonForMatStr.append(c);break;
}
}returnjsonForMatStr.toString();
}/***@paramlevel
*@return*@throws*@authorlgh
* @date /10/29-14:29*/
private String getLevelStr(intlevel) {
StringBuffer levelStr= newStringBuffer();for (int levelI = 0; levelI < level; levelI++) {
levelStr.append("\t");
}returnlevelStr.toString();
}
同样的数据输出之后就达到预期效果:
{"header":{"transSn":"e33128bb7622462ebfb2cbfcc46baa14","dateTime":"1002110000","serviceCode":"********","appId":"999999999999","bizId":"000000","version":"1.0","resType":"A","resCode":"SSS000","resMsg":"交易成功(业务附加消息:***)"},"resBody":{"operator":"lgh","rowNumStart":"1","pageRowNum":"100","pageFlag":"0","totalRowNum":"1","orderFlag":"0","orderField":"","result":[
{"flag":"1","riskCode":"00567000","riskName":"567 ****","prem":"520.00","amntOrMult":"***","amnt":"200000","polNo":"12177"}
]
}
}
原博主链接:/qq_39470733/article/details/83506752