將JSON格式的數據轉化成XML格式或者XML格式的數據轉化成JSON格式!vue json格式化電腦版中所有的關鍵字都會被著色,數據結構一目了然。很多用戶都想要去了解Java怎麼對JSON字符串進行格式化輸出的哦,一起來仔細看看吧!
/**
*
* @author lizhgb
* @date 2015-10-14
* @Modified 2017-04-28
*
*/
public final class FormatUtil {
/**
*
* @param jsonStr
* @author lizhgb
* @Date 2015-10-14 下午1:17:22
*/
public static void printJson(String jsonStr) {
System.out.println(formatJson(jsonStr));
}
/**
* 格式化
*
* @param jsonStr
* @return
* @author lizhgb
* @Date 2015-10-14 下午1:17:35
* @Modified 2017-04-28 下午8:55:35
*/
public static String formatJson(String jsonStr) {
if (null == jsonStr || "".equals(jsonStr))
return "";
StringBuilder sb = new StringBuilder();
char last = '\0';
char current = '\0';
int indent = 0;
boolean isInQuotationMarks = false;
for (int i = 0; i < jsonStr.length(); i++) {
last = current;
current = jsonStr.charAt(i);
switch (current) {
case '"':
if (last != '\\'){
isInQuotationMarks = !isInQuotationMarks;
}
sb.append(current);
break;
case '{':
case '[':
sb.append(current);
if (!isInQuotationMarks) {
sb.append('\n');
indent++;
addIndentBlank(sb, indent);
}
break;
case '}':
case ']':
if (!isInQuotationMarks) {
sb.append('\n');
indent--;
addIndentBlank(sb, indent);
}
sb.append(current);
break;
case ',':
sb.append(current);
if (last != '\\' && !isInQuotationMarks) {
sb.append('\n');
addIndentBlank(sb, indent);
}
break;
default:
sb.append(current);
}
}
return sb.toString();
}
/**
* 添加space
*
* @param sb
* @param indent
* @author lizhgb
* @Date 2015-10-14 上午10:38:04
*/
private static void addIndentBlank(StringBuilder sb, int indent) {
for (int i = 0; i < indent; i++) {
sb.append('\t');
}
}
}
輸出:
{
"content":"this is the msg content.",
"tousers":"user1|user2",
"msgtype":"texturl",
"appkey":"test",
"domain":"test",
"system":{
"wechat":{
"safe":"1"
}
},
"texturl":{
"urltype":"0",
"user1":{
"spStatus":"user01",
"workid":"work01"
},
"user2":{
"spStatus":"user02",
"workid":"work02"
}
}
}