How do I convert a JSONObject to a byte array and then convert this byte array to get back the original JSONObject? [duplicate]

半城伤御伤魂 提交于 2019-12-10 15:13:39

问题


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.


回答1:


How about this?

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

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



来源:https://stackoverflow.com/questions/36560223/how-do-i-convert-a-jsonobject-to-a-byte-array-and-then-convert-this-byte-array-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!