使用Gson和fastjson格式化JSON字符串

package com.brianway.learning.spring.helloworld.service;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;

import java.io.StringReader;

/**
 *@Author:jilongliang
 *@Email:jilongliang@sina.com
 *@Date:2015-1-5
 *@CopyRight:liangjilong
 *@Description:
 */
public class JsonFormatter {
    /**
     * 使用Gson格式化JSON字符串
     * @param content
     * @return
     */
    public static String GsonFormatter(String content){
//        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        Gson gson = new Gson();
        JsonReader reader = new JsonReader(new StringReader(content));
        reader.setLenient(true);
        JsonParser jsonPar = new JsonParser();
        JsonElement jsonEl = jsonPar.parse(reader);
        String prettyJson = gson.toJson(jsonEl);
        return prettyJson;

    }
    /**
     * 使用fastjson格式化JSON字符串
     * @param content
     * @return
     */
    public static String FastJsonFormatter(String content){
        JSONObject jsonObject = JSONObject.parseObject(content);
        String str = JSONObject.toJSONString(jsonObject);
//        String str = JSONObject.toJSONString(jsonObject, true);
        return str;

    }

    public static void main(String[] args){
        String strOption = "{
" +
                "    xAxis: {
" +
                "        type: 'category',
" +
                "        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
" +
                "    },
" +
                "    yAxis: {
" +
                "        type: 'value'
" +
                "    },
" +
                "    series: [{
" +
                "        data: [820, 932, 901, 934, 1290, 1330, 1320],
" +
                "        type: 'line'
" +
                "    }]
" +
                "}
";


        //fastjson格式化,会改变顺序
        System.out.println(JsonFormatter.FastJsonFormatter(strOption));

        //gson格式化
        System.out.println(JsonFormatter.GsonFormatter(strOption));
    }
}
{"yAxis":{"type":"value"},"xAxis":{"data":["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],"type":"category"},"series":[{"data":[820,932,901,934,1290,1330,1320],"type":"line"}]}
{"xAxis":{"type":"category","data":["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]},"yAxis":{"type":"value"},"series":[{"data":[820,932,901,934,1290,1330,1320],"type":"line"}]}
原文地址:https://www.cnblogs.com/yasepix/p/8384711.html