GSON的自定义打印格式

ruoxqz4g  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(244)

我在GSON的打印方面遇到了一些问题。GSON在打印方面有两种选择。
1.漂亮打印
1.紧凑打印
我打算使用一个修改过的Pretty Printing格式,尽管文档中说JsonPrintFormatter是用于修改输出格式的类。但我在GSON库中找不到该类!
对于为什么会出现这种情况有什么想法吗?或者我可以修改GSON打印?除此之外,任何用于修改Java语言中JSON的间距或格式的库也会很有帮助。
漂亮打印:

{
  "classname": "something",
  "type": "object",
  "version": 1,
  "properties": [
    {
      "propertyname": "something1",
      "type": "String",
      "length": 255
    },
    {
      "propertyname": "something2",
      "type": "Date",
      "length": 10
    }
  ]
}

紧凑打印:

{"classname":"something","type":"object","version":1,"properties":[{"propertyname":"something1","type":"String","length":255},{"propertyname":"something2","type":"Date","length":10}]}

我的打印样式:

{
  "classname": "something",
  "type": "object",
  "version": 1,
  "properties": [
    {"propertyname": "something1","type": "String","length": 255},
    {"propertyname": "something2","type": "Date","length": 10}
  ]
}
kqlmhetl

kqlmhetl1#

好吧,这只是目前正在进行的工作,但这应该可以处理只有一个**数组的字符串。将研究如何使它更稳定,并能够处理更复杂的结构。

private static String reformat(String og){
    String reformattable = og;
    String[] parts = reformattable.split("\\[",2);
    String arrayPart = parts[1];
    String arrayOnly = arrayPart.split("]",2)[0];
    reformattable = arrayOnly.replaceAll("\\{\n","{");
    reformattable = reformattable.replaceAll("\",\n", "\\\",");
    reformattable = reformattable.replaceAll(" +"," ");
    reformattable = reformattable.replaceAll("\\{ ","   {");
    reformattable = reformattable.replaceAll("\n }","}");

    return og.replace(arrayOnly,reformattable);
}

结果应该看起来像这样(至少对于我的简单类):

{
 "classname": "test",
 "properties": [
   {"propertyname": "1", "length": 1},
   {"propertyname": "1", "length": 1}
 ]
}

相关问题