java 如何将 JSONObject 转换为字节数组,然后转换此字节数组以取回原始 JSONObject?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36560223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I convert a JSONObject to a byte array and then convert this byte array to get back the original JSONObject?
提问by Drew
I am using the AWS JSONObjectclass. Let's say I define a JSONObjectobject like so:
我正在使用AWSJSONObject类。假设我JSONObject像这样定义了一个对象:
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:
所以 JSONObject 看起来像:
{"Field1": 35,
"Field2": {"Name1": "value1",
"Name2": 42}
}
I want to take this JSONObjectand convert it to a byte array somehow:
我想以JSONObject某种方式将其转换为字节数组:
byte[] objAsBytes = convertToBytes(obj);
where convertToBytesis some function that does this correctly. Then I would like to take this byte array and convert it back to the original JSONObjectso it still preserves its original structure.
哪里convertToBytes有正确执行此操作的函数。然后我想把这个字节数组转换回原来的,JSONObject这样它仍然保留它的原始结构。
Does anyone know how to do this? I would like to do this because I am using Amazon Kinesis and more specifically the PutRecordAPI and a PutRecordRequestrequires the data to be a ByteBuffer, so I need to convert the JSONObjectto a byte array, and then wrap the byte array as a ByteBuffer. Then, when I retrieve the record I need to convert the ByteBufferto a byte array and then get the original JSONObject.
有谁知道如何做到这一点?我想这样做是因为我使用的是 Amazon Kinesis,更具体地说是PutRecordAPI,并且 aPutRecordRequest要求数据为 a ByteBuffer,因此我需要将JSONObjecta转换为字节数组,然后将字节数组包装为ByteBuffer. 然后,当我检索记录时,我需要将其转换ByteBuffer为字节数组,然后获取原始 JSONObject。
回答by
How about this?
这个怎么样?
byte[] objAsBytes = obj.toString().getBytes("UTF-8");
I used Json.simpleto try it out, seems to work!
我用Json.simple试了一下,好像可以!

