在Java中将JSON类型转换为字节数组格式
问题描述:
我想在UDP协议中使用字节格式发送数据时遇到问题,问题是当我尝试使用json对象类型创建数据时,我无法获取数据的字节格式,这是我的示例代码:
I have a problem when I want to sending data using byte format in UDP protocol, the problem is when I try to create a data with type json object, I can't get the byte format of my data this is my sample code:
JSONObject obj = new JSONObject();
obj.put("name", "foo");
obj.put("num", new Integer(100));
obj.put("balance", new Double(1000.21));
obj.put("is_vip", new Boolean(true));
obj.put("nickname",null);
sendData = obj.getBytes(); //this is error because not have methos getBytes();
我知道我的问题,但是我找不到如何将json对象转换为字节的方法,有什么建议吗?
i know my problem but i can't found how to convert json object to byte, any suggestion ?
答
获取字符串的字节:
obj.toString().getBytes(theCharset);