使用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 = "{\n" +
                "    xAxis: {\n" +
                "        type: 'category',\n" +
                "        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']\n" +
                "    },\n" +
                "    yAxis: {\n" +
                "        type: 'value'\n" +
                "    },\n" +
                "    series: [{\n" +
                "        data: [820, 932, 901, 934, 1290, 1330, 1320],\n" +
                "        type: 'line'\n" +
                "    }]\n" +
                "}\n";


        //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"}]}

 

posted @ 2018-01-30 14:04  yasepix  阅读(4132)  评论(0编辑  收藏  举报