I have a valid JSON String that I want to tidy/format such that each property/value pair is on its own line, etc. (it currently is on one line w no spaces/line breaks).
我有一个有效的JSON字符串,我想要整理/格式化,以便每个属性/值对都在自己的行上,等等(它目前在一行w上,没有空格/换行)。
I am using the Apache Sling JSONObject
to model my JSON Object and turn it into a String, so if the Sling JSONObject
can be set to output a tidy string (which I do not think it can) that would work too.
我正在使用Apache Sling JSONObject对JSON对象建模并将其转换为字符串,因此,如果可以将Sling JSONObject设置为输出一个整洁的字符串(我认为它不能),那么它也可以工作。
If i need a 3rd party lib i would prefer one w as few dependencies as possibles (such as Jackson which only requires the std JDK libs).
如果我需要一个第三方的lib,我宁愿选择一个w,而不是尽可能少的依赖项(如Jackson,它只需要std JDK libs)。
7 个解决方案
#1
18
You don't need an outside library.
你不需要外面的图书馆。
Use the built in pretty printer in Sling's JSONObject: http://sling.apache.org/apidocs/sling5/org/apache/sling/commons/json/JSONObject.html#toString(int)
在Sling的JSONObject中使用内置的漂亮打印机:http://sling.apache.org/apidocs/sling5/slache/slinge/sling/commons/json/jsonobject.html #toString(int)
public java.lang.String toString(int indentFactor) throws JSONException
公共. lang。字符串toString(int indentFactor)抛出JSONException
Make a prettyprinted JSON text of this JSONObject. Warning: This method assumes that the data structure is acyclical.
创建这个JSONObject的预打印JSON文本。警告:此方法假定数据结构为非周期性的。
Parameters:
参数:
indentFactor - The number of spaces to add to each level of indentation.
indentFactor—为每个缩进级别添加的空格数。
Returns: a printable, displayable, portable, transmittable representation of the object, beginning with { (left brace) and ending with } (right brace).
返回:对象的可打印、可显示、可移植、可传输的表示形式,以{(左括号)开头,以}(右括号)结尾。
Throws: JSONException - If the object contains an invalid number.
抛出:JSONException—如果对象包含无效数字。
#2
32
With gson you can do:
有了gson,你可以做到:
JsonParser parser = new JsonParser();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement el = parser.parse(jsonString);
jsonString = gson.toJson(el); // done
#3
15
Many JSON libraries have a special .toString(int indentation)
method
许多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));
#4
7
+1 for JohnS's gson answer, but here's a way with the "standard" JSONObject library:
+1表示约翰斯的gson答案,但是这里有一个“标准”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<String> 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();
}
}
}
Usage:
用法:
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));
}
Output:
输出:
{
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"
}
}
}
#5
2
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;
}
#6
1
The JSON string will have a leading "[" and a trailing "]". Remove these and then use the split method from String to separate the items into an array. You can then iterate through your array and place the data into relevant areas.
JSON字符串将有一个前导“[”和一个尾“]”。删除它们,然后使用split方法从字符串中分离项目到一个数组中。然后可以遍历数组并将数据放置到相关区域。
#7
1
if your using CQ5 or any JCR based CMS as i guess :)
如果您使用CQ5或任何基于JCR的CMS,我猜:)
you can use java json parser to do the job. it has a JSONObject class and a toString() method to convert it to String.
您可以使用java json解析器来完成这项工作。它有一个JSONObject类和一个toString()方法来将它转换为String。
for further reference refer
为进一步参考参考
http://json.org/java/
#1
18
You don't need an outside library.
你不需要外面的图书馆。
Use the built in pretty printer in Sling's JSONObject: http://sling.apache.org/apidocs/sling5/org/apache/sling/commons/json/JSONObject.html#toString(int)
在Sling的JSONObject中使用内置的漂亮打印机:http://sling.apache.org/apidocs/sling5/slache/slinge/sling/commons/json/jsonobject.html #toString(int)
public java.lang.String toString(int indentFactor) throws JSONException
公共. lang。字符串toString(int indentFactor)抛出JSONException
Make a prettyprinted JSON text of this JSONObject. Warning: This method assumes that the data structure is acyclical.
创建这个JSONObject的预打印JSON文本。警告:此方法假定数据结构为非周期性的。
Parameters:
参数:
indentFactor - The number of spaces to add to each level of indentation.
indentFactor—为每个缩进级别添加的空格数。
Returns: a printable, displayable, portable, transmittable representation of the object, beginning with { (left brace) and ending with } (right brace).
返回:对象的可打印、可显示、可移植、可传输的表示形式,以{(左括号)开头,以}(右括号)结尾。
Throws: JSONException - If the object contains an invalid number.
抛出:JSONException—如果对象包含无效数字。
#2
32
With gson you can do:
有了gson,你可以做到:
JsonParser parser = new JsonParser();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement el = parser.parse(jsonString);
jsonString = gson.toJson(el); // done
#3
15
Many JSON libraries have a special .toString(int indentation)
method
许多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));
#4
7
+1 for JohnS's gson answer, but here's a way with the "standard" JSONObject library:
+1表示约翰斯的gson答案,但是这里有一个“标准”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<String> 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();
}
}
}
Usage:
用法:
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));
}
Output:
输出:
{
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"
}
}
}
#5
2
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;
}
#6
1
The JSON string will have a leading "[" and a trailing "]". Remove these and then use the split method from String to separate the items into an array. You can then iterate through your array and place the data into relevant areas.
JSON字符串将有一个前导“[”和一个尾“]”。删除它们,然后使用split方法从字符串中分离项目到一个数组中。然后可以遍历数组并将数据放置到相关区域。
#7
1
if your using CQ5 or any JCR based CMS as i guess :)
如果您使用CQ5或任何基于JCR的CMS,我猜:)
you can use java json parser to do the job. it has a JSONObject class and a toString() method to convert it to String.
您可以使用java json解析器来完成这项工作。它有一个JSONObject类和一个toString()方法来将它转换为String。
for further reference refer
为进一步参考参考
http://json.org/java/