当前位置: 代码迷 >> 综合 >> 2020-08-11json对象中存入字节数组的一个小问题
  详细解决方案

2020-08-11json对象中存入字节数组的一个小问题

热度:7   发布时间:2024-02-09 20:14:25.0

    写这篇文章,是因为在实际中遇到了这个问题,主要是json对象中,如果直接存入字节数组:byte[],那么,会默认做一个base64加密,最终存成一个字符串形式。

    下面是一个简单的demo,组成123456的字节数组,存入json对象中:

import java.util.Base64;
import com.alibaba.fastjson.JSONObject;
public class ByteInJsonDemo {public static void main(String[] args) {// encodebyte[] b = new byte[] {0x31,0x32,0x33,0x34,0x35,0x36};System.out.println(new String(b));          //123456JSONObject json = new JSONObject();json.put("data", b);byte[] b64 = Base64.getEncoder().encode(b);String str = new String(b64);System.out.println(str);                    //MTIzNDU2json.put("realdata", str);System.out.println(json);                   //{"data":"MTIzNDU2","realdata":"MTIzNDU2"}// decodebyte[] data = json.getBytes("data");System.out.println(new String(data));       //123456String value = json.getString("realdata");byte[] result = Base64.getDecoder().decode(value);System.out.println(new String(result));     //123456}
}

    我们如果将json对象最终存入mongo中,我们再来看他的值,会觉着很奇怪,主要是字节数组这里容易让我们产生迷惑。其实如果我们直接json.getBytes("data")就能得到我们原始的字节数组了,另外,如果我们按照字符串来取,那么就需要通过base64解码来还原这个字节数组了。