FastJson getBytes

标签: #Share

在使用FastJson过程中出现了

Exception in thread "main" com.alibaba.fastjson.JSONException: can not cast to int, value : [-119,80,78,71,13]

异常,现来分析其报错原因

getBytes 异常

// ImgUtilApp 具备 byte[] 变量
ImgUtilApp imgUtilApp = new ImgUtilApp();
imgUtilApp.setBytes(bytes);

// FastJson
JSONObject fastJson = (JSONObject) JSON.toJSON(imgUtilApp);

System.out.println(fastJson.getBytes("bytes"));

// 异常:
Exception in thread "main" com.alibaba.fastjson.JSONException: can not cast to int, value : [-119,80,78,71,13]

getBytes 源码

public static byte[] castToBytes(Object value) {
    if (value instanceof byte[]) {
        return (byte[])((byte[])value);
    } else if (value instanceof String) {
        return IOUtils.decodeBase64((String)value);
    } else {
        throw new JSONException("can not cast to int, value : " + value);
    }
}

// 从代码可以看出只支持 byte[]类型获取,或者 String -> Base64 转成 byte[]

正确使用方式

JSONObject fastJson = (JSONObject) JSON.toJSON(imgUtilApp);
fastJson.put("bytesDemo", bytes);
System.out.println(fastJson.getBytes("bytesDemo"));

// 主动put byte[]类型,方可直接取出

问题产生原因

  • 没有深刻认识标准JSON的数据结构,JsonObject,JsonArray,Inteager,String,Boolean…..
  • byte[] 在进行parse的时候会被主动解析成 JsonArray,因此它的类型已经被改变
  • 看到 getBytes Api 想当然的以为和 getString 一样的顺滑,但是忽略了本身数据结构的特性导致该问题的产生

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!

CV程序员的一次进步 上一篇
Docsify篇 下一篇