Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Converting a large java object to String containing json format #1176

Closed
coded9 opened this issue Oct 23, 2017 · 5 comments
Closed

Converting a large java object to String containing json format #1176

coded9 opened this issue Oct 23, 2017 · 5 comments

Comments

@coded9
Copy link

coded9 commented Oct 23, 2017

               Gson gson = null;
		GsonBuilder gsonBuilder = new GsonBuilder();
		gson = gsonBuilder.serializeNulls().create();
		return gson.toJson(this);

this refers to a large java object,I get out of memory exception while converting,also our heap size is 1 GB.Any workaround for this ?

@coded9 coded9 changed the title Converting a large object to String containing json format Converting a large java object to String containing json format Oct 23, 2017
@JakeWharton
Copy link
Contributor

There are overloads of toJson which take destination streams that you can write directly to. This saves having to create an intermediate String object and will work better on low-memory environments and with extremely large JSON objects.

@coded9
Copy link
Author

coded9 commented Oct 24, 2017

I did use this method in the below mentioned code,but it seems to use more memory compared to (gson.toJson(this))

GsonBuilder gsonBuilder = new GsonBuilder();
		gson = gsonBuilder.serializeNulls().create();
		//return gson.toJson(this);
		// OutputStream out = new ByteArrayOutputStream();
		 ByteArrayOutputStream outt = new ByteArrayOutputStream();
		JsonWriter writer = new JsonWriter(new OutputStreamWriter(outt, "UTF-8"));
        writer.beginArray();
       
            gson.toJson(this, this.getClass(), writer);
        
        writer.endArray();
        writer.close();

@JakeWharton
Copy link
Contributor

JakeWharton commented Oct 24, 2017 via email

@coded9
Copy link
Author

coded9 commented Oct 24, 2017

In the end state we need it as a String,what approach do you suggest ?

@JakeWharton
Copy link
Contributor

JakeWharton commented Oct 24, 2017 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants