简体   繁体   English

如何将大型 JSON 字符串转换为 JSON 对象?

[英]How to convert a large JSON string to JSON Object?

My spring application does a rest request to a server and the response from the server is a JSONObject string.我的 spring 应用程序向服务器发出一个休息请求,来自服务器的响应是一个 JSONObject 字符串。 The JSON string is very huge(200MB). JSON 字符串非常大(200MB)。 I want to convert the json string to a JSONObject.我想将 json 字符串转换为 JSONObject。 Below are my code for conversion:以下是我的转换代码:

exchange = restTemplate.exchange(Url, HttpMethod.POST, postEntity, String.class);
jsonObject = objectMapper.readValue(exchange.getBody(), JSONObject.class);

For a single request, it is taking 3-5 seconds for conversion.对于单个请求,转换需要 3-5 秒。 But, if there are multiple requests the conversion is taking so much time (60 seconds for 8-10 requests in parallel).但是,如果有多个请求,转换会花费很多时间(并行 8-10 个请求需要 60 秒)。 Is there any better way to do this?有没有更好的方法来做到这一点?

I'd say that transforming a 200MB chunk of JSON to an object using jackson-databind's ObjectMapper will almost always consume a lot of computing time and furthermore huge amounts of memory.我想说的是,使用 jackson-databind 的ObjectMapper将 200MB 的 JSON 块转换为对象几乎总是会消耗大量计算时间和大量内存。

If you don't need the whole object represented by the JSON in memory at a single time, ie chunks of it will suffice, I would advise to switch to an approach that utilizes jackson's streaming API .如果您一次不需要内存中由 JSON 表示的整个对象,即它的块就足够了,我建议切换到利用jackson 的流 API 的方法 You can combine it with databind on smaller subsets of the JSON, passing the resulting DTOs to some consumer (kind of visitor pattern).您可以将它与 JSON 的较小子集上的 databind 结合起来,将生成的 DTO 传递给某个使用者(某种访问者模式)。

I hope this is of any help for your special use-case.我希望这对您的特殊用例有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM