关于json:将json串以标准格式输出到文件中友好显示

82次阅读

共计 1869 个字符,预计需要花费 5 分钟才能阅读完成。

1 应用阿里的 FastJson

1.1 我的项目的 pom.xml 依赖

<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>1.2.58</version>
</dependency>
public static void main(String[] args) {

    String jsonString = "{\"_index\":\"book_shop\",\"_type\":\"it_book\",\"_id\":\"1\",\"_score\":1.0," +
            "\"_source\":{\"name\": \"Java 编程思维(第 4 版)\",\"author\": \"[ 美] Bruce Eckel\",\"category\": \" 编程语言 \"," +
            "\"price\": 109.0,\"publisher\": \" 机械工业出版社 \",\"date\": \"2007-06-01\",\"tags\": [\"Java\", \" 编程语言 \"]}}";

    JSONObject object = JSONObject.parseObject(jsonString);
    String pretty = JSON.toJSONString(object, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue, 
            SerializerFeature.WriteDateUseDateFormat);

    System.out.println(pretty);
}

 格式化输入后的后果:

阐明: FastJson 通过 Tab 键进行换行后的格式化.

{
    "_index":"book_shop",
    "_type":"it_book",
    "_source":{
        "date":"2007-06-01",
        "author":"[美] Bruce Eckel",
        "price":109.0,
        "name":"Java 编程思维(第 4 版)",
        "publisher":"机械工业出版社",
        "category":"编程语言",
        "tags":[
            "Java",
            "编程语言"
        ]
    },
    "_id":"1",
    "_score":1.0
}

1.2 应用谷歌 GSON

public static void main(String[] args) {
    
    String jsonString = "{\"_index\":\"book_shop\",\"_type\":\"it_book\",\"_id\":\"1\",\"_score\":1.0," +
            "\"_source\":{\"name\": \"Java 编程思维(第 4 版)\",\"author\": \"[ 美] Bruce Eckel\",\"category\": \" 编程语言 \"," +
            "\"price\": 109.0,\"publisher\": \" 机械工业出版社 \",\"date\": \"2007-06-01\",\"tags\": [\"Java\", \" 编程语言 \"]}}";
    
    String pretty = toPrettyFormat(jsonString)
    
    System.out.println(pretty);
}

/**
 * 格式化输入 JSON 字符串
 * @return 格式化后的 JSON 字符串
 */
private 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);
}

阐明: Gson 应用 2 个空格作为换行后的格局转换.

{
  "_index": "book_shop",
  "_type": "it_book",
  "_id": "1",
  "_score": 1.0,
  "_source": {
    "name": "Java 编程思维(第 4 版)",
    "author": "[美] Bruce Eckel",
    "category": "编程语言",
    "price": 109.0,
    "publisher": "机械工业出版社",
    "date": "2007-06-01",
    "tags": [
      "Java",
      "编程语言"
    ]
  }
}

正文完
 0