首页 > 学院 > 开发设计 > 正文

json字符串格式化

2019-11-06 06:16:58
字体:
来源:转载
供稿:网友

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(); }
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表