json字串格式化
阿新 • • 發佈:2019-02-01
1.使用Jackson的ObjectMapper來實現,這種效果比較緊湊
先引入jackson的jar包:
<dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.6.0-rc2</version> </dependency>
json格式化:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.INDENT_OUTPUT, Boolean.TRUE);// json格式化設定(INDENT_OUTPUT表示支援縮排)
2.自己寫方法格式化,這種方式顯示效果比較好
public static String formatJson(String content) {
StringBuffer sb = new StringBuffer();
int index = 0;
int count = 0;
while(index < content.length()){
char ch = content.charAt(index);
if(ch == '{' || ch == '['){
sb.append(ch);
sb.append('\n');
count++;
for (int i = 0; i < count; i++) {
sb.append('\t' );
}
}
else if(ch == '}' || ch == ']'){
sb.append('\n');
count--;
for (int i = 0; i < count; i++) {
sb.append('\t');
}
sb.append(ch);
}
else if(ch == ','){
sb.append(ch);
sb.append('\n');
for (int i = 0; i < count; i++) {
sb.append('\t');
}
}
else {
sb.append(ch);
}
index ++;
}
return sb.toString();
}