Custom PrintFormatting for GSON

前端 未结 1 1446
被撕碎了的回忆
被撕碎了的回忆 2021-01-26 10:21

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

相关标签:
1条回答
  • 2021-01-26 10:57

    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}
     ]
    }
    
    0 讨论(0)
提交回复
热议问题