Java map list 转json格式化美化打印输出
原创 everyBody 发表于:2022-04-04 16:48:41
  阅读 :232   收藏   编辑

image.png

 public static void main(String[] args) {
    List<Bean> data = new ArrayList<>();
    data.add(new Bean(1, "Zhang.san", "Shanghai"));
    data.add(new Bean(2, "Li.si", "Beijing"));
    String formatStr = JsonFormat.format(JSON.toJSONString(data));
    System.out.println(formatStr);
  }

  @Data
  @AllArgsConstructor
  static class Bean {
    private Integer id;
    private String name;
    private String addrs;
  }

工具类

package com.fg.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;


public class JsonFormat {
  public static String format(String jsonStr) {
    try {
      ByteArrayInputStream in = new ByteArrayInputStream(jsonStr.getBytes());
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      char ch;
      int read;
      int space = 0;
      while ((read = in.read()) > 0) {
        ch = (char) read;
        switch (ch) {
          case '{': {
            space = outputAndRightMove(space, ch, out);
            break;
          }
          case '[': {
            out.write(ch);
            space += 2;
            break;
          }
          case '}': {
            space = outputAndLeftMove(space, ch, out);
            break;
          }
          case ']': {
            outputNewline(out);
            space = outputAndLeftMove(space, ch, out);
            break;
          }
          case ',': {
            out.write(ch);
            // outputNewline(out);
            // out.write(getBlankingStringBytes(space));
            break;
          }
          default: {
            out.write(ch);
            break;
          }
        }
      }
      return out.toString();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return null;
  }

  public static int outputAndRightMove(int space, char ch, ByteArrayOutputStream out) throws IOException {
    //换行
    outputNewline(out);
    //向右缩进
    out.write(getBlankingStringBytes(space));
    out.write(ch);
    // outputNewline(out);
    space += 2;
    //再向右缩进多两个字符
    // out.write(getBlankingStringBytes(space));
    return space;
  }

  public static int outputAndLeftMove(int space, char ch, ByteArrayOutputStream out) throws IOException {
    // outputNewline(out);
    space -= 2;
    // out.write(getBlankingStringBytes(space));
    out.write(ch);
    return space;
  }

  public static byte[] getBlankingStringBytes(int space) {
    StringBuilder sb = new StringBuilder("");
    for (int i = 0; i < space; i++) {
      sb.append(" ");
    }
    return sb.toString().getBytes();
  }

  public static void outputNewline(ByteArrayOutputStream out) {
    out.write('\n');
  }
}