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

来源:互联网 发布:php 高德地图api 编辑:程序博客网 时间:2024/06/10 10:40

最近项目用到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"}
阅读全文
0 0
原创粉丝点击