如何将JSONObject转换为字节数组,然后将该字节数组转换为取回原始JSONObject? [英] How do I convert a JSONObject to a byte array and then convert this byte array to get back the original JSONObject?

查看:1465
本文介绍了如何将JSONObject转换为字节数组,然后将该字节数组转换为取回原始JSONObject?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 AWS JSONObject.假设我像这样定义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);

因此JSONObject看起来像:

So the JSONObject looks like:

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

我想将此JSONObject并以某种方式将其转换为字节数组:

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

byte[] objAsBytes = convertToBytes(obj);

其中,convertToBytes是一些可以正确执行此功能的函数.然后,我想获取此字节数组并将其转换回原始的JSONObject,以便它仍保留其原始结构.

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.

有人知道该怎么做吗?我想这样做是因为我正在使用Amazon Kinesis,更具体地说是PutRecord API,而PutRecordRequest要求数据为ByteBuffer,因此我需要将JSONObject转换为字节数组,并且然后将字节数组包装为ByteBuffer.然后,当我检索记录时,我需要将ByteBuffer转换为字节数组,然后获取原始的JSONObject.

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.

推荐答案

如何?

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

我使用 Json.simple 进行了尝试,似乎可行!

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

这篇关于如何将JSONObject转换为字节数组,然后将该字节数组转换为取回原始JSONObject?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆