user2409693
user2409693

Reputation:

Gson library, cast JsonObject to MyObject

Im currently using this code to create Objects out of JsonStrings from my Server:

JsonParser parser = new JsonParser();
JsonObject myJsonObject = (JsonObject) parser.parse(myInputStreamReader);
MyObject myObject = new Gson().fromJson(myJsonObject.toString(), MyObject.class);

This works pretty good in most cases, but sometimes, the objects are pretty big and therefor myJsonObject.toString() causes a java.lang.OutOfMemoryError. Is there a possibility to cast JsonObjects directly to the specified object without casting them to a string first?

I already bypassed the OutOfMemmoryError for JsonObject-creation by using the StreamReader instead of a String and now i have exactly the same problem again, just a few lines under it :/

Upvotes: 0

Views: 452

Answers (1)

JB Nizet
JB Nizet

Reputation: 691943

Why are you parsing the JSON stream to a JSON object, then transforming back the JSON object to a string, then transforming back this string to a MyObject? Just do the last part, and everything will be much faster, and use less memory.

MyObject myObject = new Gson().fromJson(myInputStreamReader, MyObject.class);

Upvotes: 1

Related Questions