convert JSON Type to Byte array format in java

viyancs picture viyancs · Apr 11, 2012 · Viewed 81.7k times · Source

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();

i know my problem but i can't found how to convert json object to byte, any suggestion ?

Answer

MByD picture MByD · Apr 11, 2012

Get the bytes of the string:

obj.toString().getBytes(theCharset);