我使用JSON -simple,我需要漂亮地打印JSON数据(使其更易于阅读)。
我还没能在那个库中找到这个功能。 这通常是如何实现的?
我使用JSON -simple,我需要漂亮地打印JSON数据(使其更易于阅读)。
我还没能在那个库中找到这个功能。 这通常是如何实现的?
当前回答
这招对我很管用,用了杰克逊的话:
mapper.writerWithDefaultPrettyPrinter().writeValueAsString(JSONString)
其他回答
与杰克逊(com.fasterxml.jackson.databind):
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject))
如何启用漂亮的JSON打印输出(Jackson)
我知道这已经在答案中,但我想在这里单独写它,因为很可能您已经将Jackson作为依赖项,因此您需要的只是额外的一行代码
大多数现有的答案要么依赖于一些外部库,要么需要一个特殊的Java版本。下面是一个简单的代码来漂亮地打印一个JSON字符串,只使用一般的Java api(在Java 7中更高;虽然还没有尝试过旧版本)。
基本思想是基于JSON中的特殊字符来调整格式。例如,如果观察到'{'或'[',代码将创建一个新行并增加缩进级别。
免责声明:我只测试了一些简单的JSON情况(基本的键值对,列表,嵌套JSON),所以它可能需要一些工作更一般的JSON文本,如字符串值内引号,或特殊字符(\n, \t等)。
/**
* A simple implementation to pretty-print JSON file.
*
* @param unformattedJsonString
* @return
*/
public static String prettyPrintJSON(String unformattedJsonString) {
StringBuilder prettyJSONBuilder = new StringBuilder();
int indentLevel = 0;
boolean inQuote = false;
for(char charFromUnformattedJson : unformattedJsonString.toCharArray()) {
switch(charFromUnformattedJson) {
case '"':
// switch the quoting status
inQuote = !inQuote;
prettyJSONBuilder.append(charFromUnformattedJson);
break;
case ' ':
// For space: ignore the space if it is not being quoted.
if(inQuote) {
prettyJSONBuilder.append(charFromUnformattedJson);
}
break;
case '{':
case '[':
// Starting a new block: increase the indent level
prettyJSONBuilder.append(charFromUnformattedJson);
indentLevel++;
appendIndentedNewLine(indentLevel, prettyJSONBuilder);
break;
case '}':
case ']':
// Ending a new block; decrese the indent level
indentLevel--;
appendIndentedNewLine(indentLevel, prettyJSONBuilder);
prettyJSONBuilder.append(charFromUnformattedJson);
break;
case ',':
// Ending a json item; create a new line after
prettyJSONBuilder.append(charFromUnformattedJson);
if(!inQuote) {
appendIndentedNewLine(indentLevel, prettyJSONBuilder);
}
break;
default:
prettyJSONBuilder.append(charFromUnformattedJson);
}
}
return prettyJSONBuilder.toString();
}
/**
* Print a new line with indention at the beginning of the new line.
* @param indentLevel
* @param stringBuilder
*/
private static void appendIndentedNewLine(int indentLevel, StringBuilder stringBuilder) {
stringBuilder.append("\n");
for(int i = 0; i < indentLevel; i++) {
// Assuming indention using 2 spaces
stringBuilder.append(" ");
}
}
这将是一个公共方法,用于打印对象的漂亮版本(你需要安装Gson依赖项:
import com.google.gson.GsonBuilder;
...
public void printMe(){
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String prettyJSON = gson.toJson(this);
System.out.println(printable);
}
你可以使用小的json库
String jsonstring = ....;
JsonValue json = JsonParser.parse(jsonstring);
String jsonIndendedByTwoSpaces = json.toPrettyString(" ");
这招对我很管用,用了杰克逊的话:
mapper.writerWithDefaultPrettyPrinter().writeValueAsString(JSONString)