tbfp
tbfp

Reputation: 153

How to convert JSONObject directly to byteArray without intermediate toString?

I have a JSONObject returned from a library. Sometimes the JSONObjects are too big and they cause an exception when applying toString to the JSONObject before applying getBytes to convert it to a byteArray. How do I convert JSONObject to ByteArray directly?

Upvotes: 1

Views: 505

Answers (2)

Rayhan Hanaputra
Rayhan Hanaputra

Reputation: 106

Try this code

ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
Json.createWriter(byteArray).write(jsonObject);
byte[] data = stream.toByteArray()

Upvotes: 2

Firat
Firat

Reputation: 43

Sample:

JSONObject obj = new JSONObject();
    obj.put("name", "foo");
    obj.put("num", new Integer(100));
    obj.put("balance", new Double(1000.21));
    obj.put("is_vip", new Boolean(true));
    obj.put("nickname",null);

Your solution :

obj.toString().getBytes(theCharset);

Upvotes: 0

Related Questions