正则表达式解决方案
在使用 JSONParser 解析数据之前,您可以使用 REGEX 从数据中删除包含 ""、[] 或 {} 的任何行。
这样的正则表达式看起来像。请记住,您可能需要根据您的操作系统调整换行符
[^\n]*(\"(\n)*\"|\[(\n)*\]|\{(\n)*\})[^\n]*
为了说明JSON数据如下的一个实例
{
"models":{},
"path":[
{
"path":"/web-profiles",
"operations":[
{
"nickname":"",
"type":"",
"responseMessages":[]
}
]
}
],
"produces":[]
}
第一次运行 replaceAll 时,结果为
{
"path":[
{
"path":"/web-profiles",
"operations":[
{
}
]
}
],
}
现在我们在“操作”JSONArray 中创建了一个空的 JSONObject。所以需要再次调用这个 replaceAll 函数,直到 JSON 字符串与之前的状态没有任何变化。
请记住,如果您在数据输入期间使用 readLine() 之类的函数,它可能会删除换行符,这会使该方法不起作用。所以解决这个问题,用这个替换你的阅读行。
json += in.readLine() + '\n';
这是我编写的一个快速程序,它从原始字符串中实际删除空 json 对象。
public static void main(String[] args){
// String from above example with newline characters intact
String json = "{\n\"models\":{},\n\"path\":[\n{\n\"path\":\"/web-profiles\",\n\"operations\":[\n{\n\"nickname\":\"\",\n\"type\":\"\",\n\"responseMessages\":[]\n}\n]\n}\n],\n\"produces\":[]\n}";
// Value from the last iteration of the while loop
String last = "";
// If there was no change from the last replaceAll call stop
while( !last.equals(json) ){
last = json;
// Same regex as above just escaped to work in a Java String
json = json.replaceAll("[^\\n]*(\\{(\\n)*\\}|\\\"(\\n)*\\\"|\\[(\\n)*\\])[^\\n]*\\n","");
}
System.out.println(json);
}