我的json是这样的:{“2”:[-1, -40, -1, -18, 0, 14, 65, 100, 111, 98, 101, 0, 100, 0, 0, 0, 0, 1, -1, -31, 35, 45, 69, 120, 105, 102, 0, 0, 77, 77, 0, 42, 0, 0, 0, 8, 0, 15, 1, 14, 0, 2, 0, 0, 0, 30, 0, 0, 8, -50, 1, 15, 0, 2, 0, 0, 0, 16, 0, 0, 8, -20, 1, 16, 0, 2, 0, 0, 0, 10, 0, 0, 8, -4, 1, 18, 0, 3, 0, 0, 0, 1, 0, 1, 0, 0, 1, 26, 0, 5, 0, 0, 0, 1, 0, 0, 9, 6, 1, 27, 0, 5, 0, 0, 0, 1, 0, 0, 9, 14, 1, 40, 0, 3, 0, 0, 0, 1, 0, 2, 0, 0, 1, 49, 0, 2, 0, 0, 0, 28, 0, 0, 9, 22, 1, 50, 0, 2, 0, 0, 0, 20, 0, 0, 9, 50, 1, 59, 0, 2, 0, 0, 0, 10, 0, 0, 9, 70, 2, 19, 0, 3, 0, 0, 0, 1, 0, 1, 0, 0]}
怎样可以把json.get("2")转成byte[]
我是把json传到servlet里,再转回json,取出来转不回byte[]
代码是这样的:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// TODO Auto-generated method stub
System.out.println("5656");
String data = request.getParameter("data");
System.out.println("在servlet里的:" + data);
JSONObject json = net.sf.json.JSONObject.fromObject(data);
Map<String, byte[]> map = (Map<String, byte[]>)json.toBean(json, Map.class);
System.out.println("--" + map.get("2"));
byte[] bytes = map.get("2"); //这里报异常,转不了,json.get("2")也是同样的情况
System.out.println(bytes[1]);
}
谢谢大家,我把字节数组转成Base64编码的字符串,传过去再解码,就可以了~
看看你取JSON的代码
格式是不是有问题,“2”后面应该是“:”吧?
Map map =Mapjson.toBean(json, Map.class);
这样去接受试试
Map<String, JsonArray> map = (Map<String, JsonArray>)json.toBean(json, Map.class);
你试试
public static void main(String[] args) throws Exception {
String data = "{\"2\":[2,-1]}";
Map<String, JSONArray> mapjsonObject = JSONObject.parseObject(data,Map.class);
JSONArray jsonArray = mapjsonObject.get("2");
byte[] bytes = new byte[jsonArray.size()];
for (int i=0;i<jsonArray.size();i++){
bytes[i] = jsonArray.getByteValue(i);
}
System.out.println(Arrays.toString(bytes));
}
你的json.get("2") 输出的是 类似于 [1,2,3] 这样的。
而byte[]是这样的 byte[] bs = {1,2,3};
其实就是【】和{}的区别.