8

I am using the AWS JSONObject class. Let's say I define a JSONObject object like so:

JSONObject obj = new JSONObject();
obj.put("Field1": 35);

JSONObject nestedObj = new JSONObject();
nestedObj.put("Name1":"value1");
nestedObj.put("Name2":42);

obj.put("Field2": nestedObj);

So the JSONObject looks like:

{"Field1": 35,
 "Field2": {"Name1": "value1",
            "Name2": 42}
}

I want to take this JSONObject and convert it to a byte array somehow:

byte[] objAsBytes = convertToBytes(obj);

where convertToBytes is some function that does this correctly. Then I would like to take this byte array and convert it back to the original JSONObject so it still preserves its original structure.

Does anyone know how to do this? I would like to do this because I am using Amazon Kinesis and more specifically the PutRecord API and a PutRecordRequest requires the data to be a ByteBuffer, so I need to convert the JSONObject to a byte array, and then wrap the byte array as a ByteBuffer. Then, when I retrieve the record I need to convert the ByteBuffer to a byte array and then get the original JSONObject.

3
  • @Pillar Sorry I'm not experienced with using JSONObject. Are you implying if I just represent the JSONObject as a String and then use the String to byte array to String conversions it should preserve the original structure of the JSONObject? Commented Apr 11, 2016 at 22:18
  • 1
    Yeah JSONObject has a toString method that will give you the textual String representation of the JSON. And it should also have a constructor that accepts a JSON String as an argument, converting it from text to the JSONObject. Commented Apr 11, 2016 at 22:19
  • 1
    JSON is just a String, so a JSONObject is nothing more than a representation of said string. If you get the byte[] of the string, you can always create the object back. Commented Apr 11, 2016 at 22:19

1 Answer 1

6

How about this?

byte[] objAsBytes = obj.toString().getBytes("UTF-8");

I used Json.simple to try it out, seems to work!

Sign up to request clarification or add additional context in comments.

1 Comment

What advantage it has over compared to base64 encoding?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.