我在使用 GSON 进行打印时遇到了一些问题。 GSON 在打印方面有两种选择。
- 漂亮的打印
- 紧凑打印
我打算使用 pretty-print 的修改形式,尽管 documentation说 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}
]
}
最佳答案
嗯,目前还在进行中,但这对于只有一个数组的字符串来说应该可以解决问题。将研究使其更加稳定并能够处理更复杂的结构。
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}
]
}
关于java - GSON 的自定义打印格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54327375/