Java中輸出JSON格式化

使用阿里的FastJson

  • pom.xml中的依賴

<dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>fastjson</artifactId>
     <version>1.2.62</version>
</dependency>
  • java中的代碼

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
//工具類
public class CommonUtils {
      //json美化的方法
		public static String prettyJson(String reqJson){
              JSONObject object = JSONObject.parseObject(reqJson);
              String prettyJson = JSON.toJSONString(object, SerializerFeature.PrettyFormat, 				   SerializerFeature.WriteMapNullValue,SerializerFeature.WriteDateUseDateFormat);
             return prettyJson;
    }
}
  • 測試類

public  class Test{
		public static void main(String arg[]) {
		String jsonstr = "{" +
				            "\"Name\":\"fanny\"," +
				            "\"age\":\"1000\"," +
				             "\"location\":\"beijing\"," +
				            "}";
		CommonUtils .prettyJson(jsonstr );
		}
}
  • 測試結果

{
	"location":"beijing",
	"age":"1000",
	"Name":"fanny"
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章