Custom PrintFormatting for GSON

这一生的挚爱 提交于 2020-12-27 05:55:36

问题


I'm having some trouble with GSON in regards to printing. GSON has two options when it comes to printing.

  1. Pretty Printing
  2. Compact Printing

I intend to use a modified form of Pretty Printing and even though the documentation says JsonPrintFormatter is the class which is used to modify the output format. I can't find that class in the GSON repository!

Any ideas on why this is the case or anyway I can modify the GSON printing? Apart from that, any libraries used to modify spacing or formatting of JSON in the Java language would also be helpful.

Pretty Print:

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

Compact Print:

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

My Print Style:

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

回答1:


Well, it's just work in progress for now, but this should do the trick for strings with only one array. Will look into to making it more stable and able to handle more complex structures.

  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);
} 

Result should look like this (at least for my simple class):

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


来源:https://stackoverflow.com/questions/54327375/custom-printformatting-for-gson

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!