1. 程式人生 > >JAVA-Gson-格式化輸出json字串

JAVA-Gson-格式化輸出json字串

使用Gson格式化輸出json字串
POM

 <dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>

GsonTest

import com.google.gson.*;

/**
 * 格式化json字串
 * @author wzx
 * @time 2018/8/19
 */
public class GsonTest {
public static void main(String[] args) { 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("compactJson:"); System.out.println(compactJson); System.out.println("prettyJson:"); System.out.println(prettyJson); }
public static String toPrettyFormat(String json) { JsonParser jsonParser = new JsonParser(); JsonObject jsonObject = jsonParser.parse(json).getAsJsonObject(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); return gson.toJson(jsonObject); } }

輸出結果:

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}]}
prettyJson:
{
  "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
    }
  ]
}