Java中json字符串的格式转换(缩进换行)

最近项目用到com.fasterxml.jackson.databind.ObjectMapper把对象转换为json字符串,但是它的输出总是只有一行的结果,如:

{"queryType":"lucene_timeseries","dataSource":"druid-test","granularity":"all","context":{"timeout":1800,"useOffheap":true,"groupByStrategy":"v2"},"aggregations":[{"type":"lucene_hyperUnique","name":"ageCount","fieldName":"age"}],"intervals":"1000/3000"}

这和我们经常看到的有缩进换行格式的json字符串有所不同,把结果输出为一行也不利于我们查看和比对,出了错误也要费心查找。

在网上搜索了一下,发现已有人针对以上的问题写了一些转换程序,但其实这里面的原理不难,所以打算自己写一下练手,同时记录在这里方便以后的取用。

  • 源程序如下:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * Created by chenyuzhi on 17-7-28.
 */
public class JsonFormater {
    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 ']': {
                        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');
    }
}
  • 测试程序如下:
import io.sugo.DataUtil.JsonFormater;
import java.io.IOException;

public class Test01 {
    public static void main(String[] args) throws IOException {
        String str = "{\"queryType\":\"lucene_timeseries\",\"dataSource\":\"druid-test\",\"granularity\":\"all\",\"context\":{\"timeout\":1800,\"useOffheap\":true,\"groupByStrategy\":\"v2\"},\"aggregations\":[{\"type\":\"lucene_hyperUnique\",\"name\":\"ageCount\",\"fieldName\":\"age\"}],\"intervals\":\"1000/3000\"}";
        println(JsonFormater.format(str));

    }

    public static void println(String str){
        System.out.println(str);
    }
}
  • 测试结果如下:
{
  "queryType":"lucene_timeseries",
  "dataSource":"druid-test",
  "granularity":"all",
  "context":
  {
    "timeout":1800,
    "useOffheap":true,
    "groupByStrategy":"v2"
  },
  "aggregations":[
    {
      "type":"lucene_hyperUnique",
      "name":"ageCount",
      "fieldName":"age"
    }
  ],
  "intervals":"1000/3000"
}
  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值