Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert JSON Type to Byte array format in java

Tags:

java

json

byte

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 ?

like image 396
viyancs Avatar asked Apr 11 '12 04:04

viyancs


People also ask

How to convert json into byte array in Java?

JSONObject obj = new JSONObject(); obj. put("name", "foo"); obj. put("num", new Integer(100)); obj. put("balance", new Double(1000.21)); obj.

Can JSON have byte array?

JSON does not support that. Use Base64. That is your library supporting it, not JSON itself. The byte array wont be stored as byte array in the JSON, JSON is a text format meant to be human readable.

What is JSON format in Java?

JSON (JavaScript Object Notation) is a lightweight, text-based, language-independent data exchange format that is easy for humans and machines to read and write. JSON can represent two structured types: objects and arrays. An object is an unordered collection of zero or more name/value pairs.

What is JSON format?

JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa).


2 Answers

Get the bytes of the string:

obj.toString().getBytes(theCharset); 
like image 120
MByD Avatar answered Oct 14 '22 22:10

MByD


Assuming the JSONObject you mention is from this, you can get the bytes like below

sendData = obj.toString().getBytes("utf-8"); 
like image 29
Agung Pratama Avatar answered Oct 14 '22 23:10

Agung Pratama