为避免在处理大型 JSON 对象时出现此错误,您需要使用流式 JSON 解析器 - http://wiki.fasterxml.com/JacksonInFiveMinutes#Streaming_API_Example。其中有两个适用于 Android:GSON
和Jackson
.
我最喜欢的是杰克逊
它真的很简单而且非常快。但当然你可以尝试使用GSON
:https ://sites.google.com/site/gson/streaming
顺便说一下,GSON
您可以在文档中找到问题的解释:
Most applications should use only the object model API.
JSON streaming is useful in just a few situations:
When it is impossible or undesirable to load the entire
object model into memory. This is most relevant on mobile
platforms where memory is limited.
在我的一个付费 Android 应用程序中,我在上下文中使用Jackson
了巨大的JSON
对象,POST
但对于 POST 查询,我使用了Spring RestTemplate
库。:http ://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/client/RestTemplate.html 。不知道对你有没有用。这是我使用库将大量序列化为LinkedHashMap
JSONJackson
并将其发布到远程服务器的代码:
public LinkedHashMap<String, Object> executeServerCommand
(String commandToExecute, LinkedHashMap<String, Object> parameters)
{
LinkedHashMap<String, Object> resultofOperation =
new LinkedHashMap<String, Object>();
ObjectMapper mapParametersToFromJackson = new ObjectMapper();
StringWriter stringRepresentation = new StringWriter();
try {
mapParametersToFromJackson.writeValue(stringRepresentation, parameters);
}
catch (JsonGenerationException e)
{
e.printStackTrace();
}
catch (JsonMappingException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
String postData = "params=" + stringRepresentation.toString();
requestHeaders.setContentLength(postData.length());
HttpEntity<String> requestEntity =
new HttpEntity<String>(postData,requestHeaders);
HttpComponentsClientHttpRequestFactory preconfiguredHTTPInstance =
new HttpComponentsClientHttpRequestFactory();
RestTemplate restfulRequest = new RestTemplate(preconfiguredHTTPInstance);
restfulRequest.setRequestFactory(preconfiguredHTTPInstance);
restfulRequest.getMessageConverters().add(new StringHttpMessageConverter());
ResponseEntity<String> responseFromServer = restfulRequest.postForEntity(NetworkCommands.MAIN_URL + commandToExecute,
requestEntity, String.class);
String serverResponseBody = responseFromServer.getBody();