How to send JSONobject over TCP? How to send JSONobject over TCP? json json

How to send JSONobject over TCP?


You are using an ObjectOutputStream to serialize your data. That serialization uses it's own implementation of converting Serializable objects to a byte representation that is then sent through your socket.

JSON is used to serialize an object into a String representation. Unfortunately, you never use the json serialization but instead try to send your JSON object through your socket.

My suggestion: turn your object to a String using

String strJson = jsonObject.toString();

then send a String using your ObjectOutputStream. On the receiving end read it as a String, then turn it back into a JSONObject by passing that String to the constructor:

JSONObject js = new JSONObject(strJson);


Just change the line to

        o.writeObject(jsonObject2.toString());

Use the .toString() method to get the String of JSONObject .

It works for me :)