簡體   English   中英

沒有空格的漂亮打印Jackson JSON?

[英]Pretty print Jackson json without whitespaces?

我有一個想與jackson一起打印的json字符串。 一般而言,以下作品:

    ObjectWriter w = new ObjectMapper()
            .writer()
            .withDefaultPrettyPrinter();

    Object obj = new ObjectMapper().readValue(json, Object.class);
    System.out.println(w.writeValueAsString(obj));

結果:

{
   "myarray" : [ {
      "field" : "val"
   } ]
}

但是:我想得到的輸出參數之間沒有空格。 那可能嗎?

所需的輸出:

{
   "myarray":[{
      "field":"val"
   }]
}

是。 您可以使用以下內容自定義DefaultPrettyPrinter

  • 使用withoutSpacesInObjectEntries()關閉對象條目內的空格

  • 將數組壓頭設置為DefaultPrettyPrinter.NopIndenter ,以便沒有空格分隔數組值。

明智的代碼,它看起來像:

DefaultPrettyPrinter pp = new DefaultPrettyPrinter()
            .withoutSpacesInObjectEntries()
            .withArrayIndenter(new DefaultPrettyPrinter.NopIndenter());

ObjectWriter w = new ObjectMapper()
            .writer()
            .with(pp);

它將以以下格式輸出JSON:

{
  "users":[{
    "name":"u1",
    "age":10
  },{
    "name":"u2",
    "age":20
  }]
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM