我在客户端上绘制了一个图像,我需要以json格式将其发送到服务器
对象json的示例(此图像有3行)
{"lines":[
[[44,23.8],[44,24.8],[44,26.8],[44,27.8],[44,28.8],[44,31.8],[44,32.8],[44,33.8],[44,34.8],[44,38.8],[44,39.8],[44,41.8],[43,44.8],[43,46.8]],
[[251,30.8],[252,30.8],[266,30.8],[274,30.8],[288,30.8],[298,30.8],[311,30.8],[320,30.8],[335,30.8],[339,29.8],[345,29.8],[352,28.8],[353,28.8]],
[[131,144.8],[134,144.8],[135,144.8],[140,142.8],[142,141.8],[153,137.8],[167,134.8],[182,131.8],[199,126.8],[213,123.8],[228,120.8],[245,115.8]]
]}
我通过在服务器端执行以下代码来解析json对象:
private static List<List<Point>> extractSignature(String jsonEncoding) {
List<List<Point>> lines = new ArrayList<List<Point>>();
Matcher lineMatcher = Pattern.compile("(\\[(?:,?\\[-?[\\d\\.]+,-?[\\d\\.]+\\])+\\])").matcher(jsonEncoding);
while (lineMatcher.find()) {
Matcher pointMatcher = Pattern.compile("\\[(-?[\\d\\.]+),(-?[\\d\\.]+)\\]").matcher(lineMatcher.group(1));
List<Point> line = new ArrayList<Point>();
lines.add(line);
while (pointMatcher.find()) {
line.add(new Point(Float.parseFloat(pointMatcher.group(1)), Float.parseFloat(pointMatcher.group(2))));
}
}
return lines;
}
它运行良好但是当图像太大(json对象很长)时我得到了异常(在lineMatcher.find()
上)
8 déc. 2015 13:17:32 org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: "Servlet.service()" pour la servlet jsp a généré une exception
java.lang.StackOverflowError
at java.util.regex.Pattern$CharProperty.match(Pattern.java:3345)
at java.util.regex.Pattern$Curly.match0(Pattern.java:3760)
at java.util.regex.Pattern$Curly.match(Pattern.java:3744)
at java.util.regex.Pattern$Ques.match(Pattern.java:3691)
at java.util.regex.Pattern$BmpCharProperty.match(Pattern.java:3366)
at java.util.regex.Pattern$Curly.match0(Pattern.java:3782)
at java.util.regex.Pattern$Curly.match(Pattern.java:3744)
at java.util.regex.Pattern$Ques.match(Pattern.java:3691)
...
我通过使用以下代码来解决此问题,但我认为这不是一个好的解决方案
int idxEnd = jsonEncoding.indexOf("]]");
while(idxEnd >= 0) {
String _line = jsonEncoding.substring(0, idxEnd + 2);
int idxBegin = _line.lastIndexOf("[["); // cas [[[
_line = _line.substring(idxBegin);
Matcher pointMatcher = Pattern.compile("\\[(-?[\\d\\.]+),(-?[\\d\\.]+)\\]").matcher(_line);
List<Point> line = new ArrayList<Point>();
lines.add(line);
while (pointMatcher.find()) {
line.add(new Point(Float.parseFloat(pointMatcher.group(1)), Float.parseFloat(pointMatcher.group(2))));
}
jsonEncoding = jsonEncoding.substring(idxEnd + 3);
idxEnd = jsonEncoding.indexOf("]]");
}
所以关于上述正则表达式的问题:(\\[(?:,?\\[-?[\\d\\.]+,-?[\\d\\.]+\\])+\\])
可以更改以使其正常工作吗?
非常感谢
答案 0 :(得分:0)
所以关于上面正则表达式的问题:
def loadData(dest=None): data = someDBRequest() if dest: try: with open(dest, 'w') as fh: json.dump(data, fh) except IOError: pass return data
可以更改以使其正常工作吗?
根据您的问题和regex101.com/r/gP7tM1/2中的示例数据,您可以将表达式简化为不等效但足够try
,i。即
(\\[(?:,?\\[-?[\\d\\.]+,-?[\\d\\.]+\\])+\\])
。