Java 格式化输出JSON字符串的2种实现操作
1使用阿里的FastJson
1.1项目的pom.xml依赖
com.alibaba fastjson 1.2.58
1.2Java示例代码
(1)导入的包:
com.alibaba.fastjson.JSON; importcom.alibaba.fastjson.JSONObject; importcom.alibaba.fastjson.serializer.SerializerFeature;
(2)测试代码:
其中JSON字符串为:
{"_index":"book_shop","_type":"it_book","_id":"1","_score":1.0,"_source":{"name":"Java编程思想(第4版)","author":"[美]BruceEckel","category":"编程语言","price":109.0,"publisher":"机械工业出版社","date":"2007-06-01","tags":["Java","编程语言"]}}
publicstaticvoidmain(String[]args){ StringjsonString="{\"_index\":\"book_shop\",\"_type\":\"it_book\",\"_id\":\"1\",\"_score\":1.0,"+ "\"_source\":{\"name\":\"Java编程思想(第4版)\",\"author\":\"[美]BruceEckel\",\"category\":\"编程语言\","+ "\"price\":109.0,\"publisher\":\"机械工业出版社\",\"date\":\"2007-06-01\",\"tags\":[\"Java\",\"编程语言\"]}}"; JSONObjectobject=JSONObject.parseObject(jsonString); Stringpretty=JSON.toJSONString(object,SerializerFeature.PrettyFormat,SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat); System.out.println(pretty); }
(3)格式化输出后的结果:
说明:FastJson通过Tab键进行换行后的格式化.
{ "_index":"book_shop", "_type":"it_book", "_source":{ "date":"2007-06-01", "author":"[美]BruceEckel", "price":109.0, "name":"Java编程思想(第4版)", "publisher":"机械工业出版社", "category":"编程语言", "tags":[ "Java", "编程语言" ] }, "_id":"1", "_score":1.0 }
2使用谷歌的Gson
2.1项目的pom.xml依赖
com.google.code.gson gson 2.2.4
2.2Java示例代码
(1)导入的包:
importcom.google.gson.Gson; importcom.google.gson.GsonBuilder; importcom.google.gson.JsonArray; importcom.google.gson.JsonElement; importcom.google.gson.JsonObject; importcom.google.gson.JsonParser;
(2)测试代码:
JSON字符串与上述测试代码相同.
publicstaticvoidmain(String[]args){ StringjsonString="{\"_index\":\"book_shop\",\"_type\":\"it_book\",\"_id\":\"1\",\"_score\":1.0,"+ "\"_source\":{\"name\":\"Java编程思想(第4版)\",\"author\":\"[美]BruceEckel\",\"category\":\"编程语言\","+ "\"price\":109.0,\"publisher\":\"机械工业出版社\",\"date\":\"2007-06-01\",\"tags\":[\"Java\",\"编程语言\"]}}"; Stringpretty=toPrettyFormat(jsonString) System.out.println(pretty); } /** *格式化输出JSON字符串 *@return格式化后的JSON字符串 */ privatestaticStringtoPrettyFormat(Stringjson){ JsonParserjsonParser=newJsonParser(); JsonObjectjsonObject=jsonParser.parse(json).getAsJsonObject(); Gsongson=newGsonBuilder().setPrettyPrinting().create(); returngson.toJson(jsonObject); }
(3)格式化输出后的结果:
说明:Gson使用2个空格作为换行后的格式转换.
{ "_index":"book_shop", "_type":"it_book", "_id":"1", "_score":1.0, "_source":{ "name":"Java编程思想(第4版)", "author":"[美]BruceEckel", "category":"编程语言", "price":109.0, "publisher":"机械工业出版社", "date":"2007-06-01", "tags":[ "Java", "编程语言" ] } }
以上这篇Java格式化输出JSON字符串的2种实现操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。