将json串以标准格式输出到文件中友好显示
1 使用阿里的FastJson
1.1 项目的pom.xml依赖
com.alibaba
fastjson
1.2.58
public static void main(String[] args) {String jsonString = "{\"_index\":\"book_shop\",\"_type\":\"it_book\",\"_id\":\"1\",\"_score\":1.0," +
"\"_source\":{\"name\": \"Java编程思想(第4版)\",\"author\": \"[美] Bruce Eckel\",\"category\": \"编程语言\"," +
"\"price\": 109.0,\"publisher\": \"机械工业出版社\",\"date\": \"2007-06-01\",\"tags\": [ \"Java\", \"编程语言\" ]}}";
JSONObject object = JSONObject.parseObject(jsonString);
String pretty = JSON.toJSONString(object, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteDateUseDateFormat);
System.out.println(pretty);
} 格式化输出后的结果:说明: FastJson通过Tab键进行换行后的格式化.{
"_index":"book_shop",
"_type":"it_book",
"_source":{
"date":"2007-06-01",
"author":"[美] Bruce Eckel",
"price":109.0,
"name":"Java编程思想(第4版)",
"publisher":"机械工业出版社",
"category":"编程语言",
"tags":[
"Java",
"编程语言"
]
},
"_id":"1",
"_score":1.0
}
1.2 使用谷歌GSON
public static void main(String[] args) {String jsonString = "{\"_index\":\"book_shop\",\"_type\":\"it_book\",\"_id\":\"1\",\"_score\":1.0," +
"\"_source\":{\"name\": \"Java编程思想(第4版)\",\"author\": \"[美] Bruce Eckel\",\"category\": \"编程语言\"," +
"\"price\": 109.0,\"publisher\": \"机械工业出版社\",\"date\": \"2007-06-01\",\"tags\": [ \"Java\", \"编程语言\" ]}}";
String pretty = toPrettyFormat(jsonString)System.out.println(pretty);
}/**
* 格式化输出JSON字符串
* @return 格式化后的JSON字符串
*/
private static String toPrettyFormat(String json) {
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = jsonParser.parse(json).getAsJsonObject();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(jsonObject);
}
【将json串以标准格式输出到文件中友好显示】说明: Gson使用2个空格作为换行后的格式转换.
{
"_index": "book_shop",
"_type": "it_book",
"_id": "1",
"_score": 1.0,
"_source": {
"name": "Java编程思想(第4版)",
"author": "[美] Bruce Eckel",
"category": "编程语言",
"price": 109.0,
"publisher": "机械工业出版社",
"date": "2007-06-01",
"tags": [
"Java",
"编程语言"
]
}
}
推荐阅读
- 即将到手三百万
- 发小的串门
- 思友人
- 一起来学习C语言的字符串转换函数
- 那些反串过的艺人-最是美色如醉人
- 20210307《挑战赛怂人胆》【能量将帅挑战赛(01)】
- 蓝桥杯试题
- 苍灵十二将I|苍灵十二将I 第一百二十五章 关门猎兽
- 字符串拼接成段落,换行符(\n)如何只执行n-1次
- 那条灰色的人行道