GSON的自定义打印格式

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

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

  1. {
  2. "classname": "something",
  3. "type": "object",
  4. "version": 1,
  5. "properties": [
  6. {
  7. "propertyname": "something1",
  8. "type": "String",
  9. "length": 255
  10. },
  11. {
  12. "propertyname": "something2",
  13. "type": "Date",
  14. "length": 10
  15. }
  16. ]
  17. }

紧凑打印:

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

我的打印样式:

  1. {
  2. "classname": "something",
  3. "type": "object",
  4. "version": 1,
  5. "properties": [
  6. {"propertyname": "something1","type": "String","length": 255},
  7. {"propertyname": "something2","type": "Date","length": 10}
  8. ]
  9. }
kqlmhetl

kqlmhetl1#

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

  1. private static String reformat(String og){
  2. String reformattable = og;
  3. String[] parts = reformattable.split("\\[",2);
  4. String arrayPart = parts[1];
  5. String arrayOnly = arrayPart.split("]",2)[0];
  6. reformattable = arrayOnly.replaceAll("\\{\n","{");
  7. reformattable = reformattable.replaceAll("\",\n", "\\\",");
  8. reformattable = reformattable.replaceAll(" +"," ");
  9. reformattable = reformattable.replaceAll("\\{ "," {");
  10. reformattable = reformattable.replaceAll("\n }","}");
  11. return og.replace(arrayOnly,reformattable);
  12. }

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

  1. {
  2. "classname": "test",
  3. "properties": [
  4. {"propertyname": "1", "length": 1},
  5. {"propertyname": "1", "length": 1}
  6. ]
  7. }
展开查看全部

相关问题