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.

Drew
  • 1,277
  • 3
  • 21
  • 39
  • @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`? – Drew Apr 11 '16 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`. – Savior Apr 11 '16 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. – dambros Apr 11 '16 at 22:19

1 Answers1

6

How about this?

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

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