我想我需要重写我的应用程序的一些模块,因为当渲染的实体数量增加,失败和错误时。目前,我正在使用Jackson
和HttpClient
。我信任杰克逊,有些东西告诉我问题是第二个问题。 HttpClient
可以处理大量回复吗? (f.e this one它约有400行)
除此之外,在我的应用程序中,我为了解析请求而采取的方式是这样的:
public Object handle(HttpResponse response, String rootName) {
try {
String json = EntityUtils.toString(response.getEntity());
// better "new BasicResponseHandler().handleResponse(response)" ????
int statusCode = response.getStatusLine().getStatusCode();
if ( statusCode >= 200 && statusCode < 300 ) {
return createObject(json, rootName);
}
else{
return null;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Object createObject (String json, String rootName) {
try {
this.root = this.mapper.readTree(json);
String className = Finder.findClassName(rootName);
Class clazz = this.getObjectClass(className);
return mapper.treeToValue(root.get(rootName), clazz);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
如何通过大响应来改进这段代码以提高效率?
提前致谢!
答案 0 :(得分:2)
无需创建String json
,因为ObjectMapper#readTree
也可以接受InputStream
。例如,这会更有效:
public Object handle(HttpResponse response, String rootName) {
try {
int statusCode = response.getStatusLine().getStatusCode();
if ( statusCode >= 200 && statusCode < 300 ) {
return createObject(response.getEntity().getContent(), rootName);
}
else{
return null;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Object createObject (InputStream json, String rootName) {
try {
this.root = this.mapper.readTree(json);
String className = Finder.findClassName(rootName);
Class clazz = this.getObjectClass(className);
return mapper.treeToValue(root.get(rootName), clazz);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
答案 1 :(得分:0)
我已经处理了1000多行json响应而没有问题,所以这不应该是一个问题。至于更好的方法,谷歌GSON是惊人的,它会将你的json映射到你的java对象,没有任何特殊的解析代码。
答案 2 :(得分:0)
我猜你可以将数据读取到一个好的旧StringBuffer。像
这样的东西HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
InputStream is = AndroidHttpClient.getUngzippedContent(httpEntity);
br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder(8192);
String s;
while ((s = br.readLine()) != null) sb.append(s);
}