将JSON字符串转换为漂亮的打印(Java,Gson )(范例)

・1 分钟阅读

这是将JSON字符串转换为漂亮打印版本的方法。


/**
 * Convert a JSON string to pretty print version
 * @param jsonString
 * @return
 */
 public static String toPrettyFormat(String jsonString) 
 {
 JsonParser parser = new JsonParser();
 JsonObject json = parser.parse(jsonString).getAsJsonObject();

 Gson gson = new GsonBuilder().setPrettyPrinting().create();
 String prettyJson = gson.toJson(json);

 return prettyJson;
 }

使用它的方式:


@Test
public void testPrettyPrint()
{
 String compactJson ="{"playerID":1234,"name":"Test","itemList":[{"itemID":1,"name":"Axe","atk":12,"def":0},{"itemID":2,"name":"Sword","atk":5,"def":5},{"itemID":3,"name":"Shield","atk":0,"def":10}]}";

 String prettyJson = toPrettyFormat(compactJson);

 System.out.println("Compact:n" + compactJson);
 System.out.println("Pretty:n" + prettyJson);
}

示例输出:

Xn_warm profile image