赞
踩
关系图:
- 解析JSON文本为带格式JSON文本
- public final class FormatJsonUtil {
- /**
- * 打印输入到控制台
- *
- * @param jsonStr
- */
- public static void printJson(String jsonStr) {
- System.out.println(formatJson(jsonStr));
- }
- /**
- * 格式化
- *
- * @param jsonStr
- */
- 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; // "{\"planId\": \"\"}"
- } // T F T F
- 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
- */
- private static void addIndentBlank(StringBuilder sb, int indent) {
- for (int i = 0; i < indent; i++) {
- sb.append('\t');
- }
- }
-
- }
- Encode代码示例:
- import com.alibaba.fastjson.JSON;
-
- Group group = new Group();
- group.setId(0L);
- group.setName("admin");
- User guestUser = new User();
- guestUser.setId(2L);
- guestUser.setName("guest");
- User rootUser = new User();
- rootUser.setId(3L);
- rootUser.setName("root");
- group.getUsers().add(guestUser);
- group.getUsers().add(rootUser);
- String jsonString = JSON.toJSONString(group);
- System.out.println(jsonString);
-
- Decode 代码示例:
- Group group2 = JSON.parseObject(jsonString, Group.class);
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。