用于Java的JSON String tidy / formatter

我有一个有效的JSON字符串,我想整理/格式化,使每个属性/值对在它自己的行等等(它当前在一行上没有空格/换行符)。

我正在使用Apache Sling JSONObject来建模我的JSON对象并将其转换为String,因此如果Sling JSONObject可以设置为输出一个整齐的字符串(我认为它不能)也可以。

如果我需要第三方lib,我宁愿选择一个尽可能少的依赖项(例如Jackson只需要std JDK库)。

您不需要外部库。

在Sling的JSONObject中使用内置漂亮的打印机: http ://sling.apache.org/apidocs/sling5/org/apache/sling/commons/json/JSONObject.html#toString(int)

public java.lang.String toString(int indentFactor)抛出JSONException

制作一个这个JSONObject的漂亮的JSON文本。 警告:此方法假定数据结构是非周期性的。

参数:

indentFactor – 要添加到每个缩进级别的空格数。

返回:对象的可打印,可显示,可移动,可传输的表示,以{(左括号)开头,以}结尾(右括号)。

抛出:JSONException – 如果对象包含无效的数字。

使用gson,您可以:

 JsonParser parser = new JsonParser(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonElement el = parser.parse(jsonString); jsonString = gson.toJson(el); // done 

许多JSON库都有一个特殊的.toString(int indentation)方法

 // if it's not already, convert to a JSON object JSONObject jsonObject = new JSONObject(jsonString); // To string method prints it with specified indentation System.out.println(jsonObject.toString(4)); 

为JohnS的gson答案+1,但这是“标准”JSONObject库的一种方式:

 public class JsonFormatter{ public static String format(final JSONObject object) throws JSONException{ final JsonVisitor visitor = new JsonVisitor(4, ' '); visitor.visit(object, 0); return visitor.toString(); } private static class JsonVisitor{ private final StringBuilder builder = new StringBuilder(); private final int indentationSize; private final char indentationChar; public JsonVisitor(final int indentationSize, final char indentationChar){ this.indentationSize = indentationSize; this.indentationChar = indentationChar; } private void visit(final JSONArray array, final int indent) throws JSONException{ final int length = array.length(); if(length == 0){ write("[]", indent); } else{ write("[", indent); for(int i = 0; i < length; i++){ visit(array.get(i), indent + 1); } write("]", indent); } } private void visit(final JSONObject obj, final int indent) throws JSONException{ final int length = obj.length(); if(length == 0){ write("{}", indent); } else{ write("{", indent); final Iterator keys = obj.keys(); while(keys.hasNext()){ final String key = keys.next(); write(key + " :", indent + 1); visit(obj.get(key), indent + 1); if(keys.hasNext()){ write(",", indent + 1); } } write("}", indent); } } private void visit(final Object object, final int indent) throws JSONException{ if(object instanceof JSONArray){ visit((JSONArray) object, indent); } else if(object instanceof JSONObject){ visit((JSONObject) object, indent); } else{ if(object instanceof String){ write("\"" + (String) object + "\"", indent); } else{ write(String.valueOf(object), indent); } } } private void write(final String data, final int indent){ for(int i = 0; i < (indent * indentationSize); i++){ builder.append(indentationChar); } builder.append(data).append('\n'); } @Override public String toString(){ return builder.toString(); } } } 

用法:

 public static void main(final String[] args) throws JSONException{ final JSONObject obj = new JSONObject("{\"glossary\":{\"title\": \"example glossary\", \"GlossDiv\":{\"title\": \"S\", \"GlossList\":{\"GlossEntry\":{\"ID\": \"SGML\", \"SortAs\": \"SGML\", \"GlossTerm\": \"Standard Generalized Markup Language\", \"Acronym\": \"SGML\", \"Abbrev\": \"ISO 8879:1986\", \"GlossDef\":{\"para\": \"A meta-markup language, used to create markup languages such as DocBook.\", \"GlossSeeAlso\": [\"GML\", \"XML\"]}, \"GlossSee\": \"markup\"}}}}}"); System.out.println(JsonFormatter.format(obj)); } 

输出:

 { glossary : { title : "example glossary" , GlossDiv : { GlossList : { GlossEntry : { SortAs : "SGML" , GlossDef : { GlossSeeAlso : [ "GML" "XML" ] , para : "A meta-markup language, used to create markup languages such as DocBook." } , GlossSee : "markup" , GlossTerm : "Standard Generalized Markup Language" , ID : "SGML" , Acronym : "SGML" , Abbrev : "ISO 8879:1986" } } , title : "S" } } } 
  public static String formatJSONStr(final String json_str, final int indent_width) { final char[] chars = json_str.toCharArray(); final String newline = System.lineSeparator(); String ret = ""; boolean begin_quotes = false; for (int i = 0, indent = 0; i < chars.length; i++) { char c = chars[i]; if (c == '\"') { ret += c; begin_quotes = !begin_quotes; continue; } if (!begin_quotes) { switch (c) { case '{': case '[': ret += c + newline + String.format("%" + (indent += indent_width) + "s", ""); continue; case '}': case ']': ret += newline + ((indent -= indent_width) > 0 ? String.format("%" + indent + "s", "") : "") + c; continue; case ':': ret += c + " "; continue; case ',': ret += c + newline + (indent > 0 ? String.format("%" + indent + "s", "") : ""); continue; default: if (Character.isWhitespace(c)) continue; } } ret += c + (c == '\\' ? "" + chars[++i] : ""); } return ret; } 

JSON字符串将具有前导“[”和尾随“]”。 删除这些,然后使用String中的split方法将项目分成一个数组。 然后,您可以遍历数组并将数据放入相关区域。

如果您使用CQ5或任何基于JCR的CMS,我猜:)

你可以使用java json解析器来完成这项工作。 它有一个JSONObject类和一个toString()方法将它转换为String。

供进一步参考参考

http://json.org/java/