How to send Json object through java sockets?

How do you send Json object's through sockets preferable through ObjectOutputStream class in java this is what I got so far

    s = new Socket("192.168.0.100", 7777);
    ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
    JSONObject object = new JSONObject();
    object.put("type", "CONNECT");
    out.writeObject(object);

But this gives an java.io.streamcorruptedexception exception any suggestions?

Jon Skeet
people
quotationmark

Instead of using ObjectOutputStream, you should create an OutputStreamWriter, then use that to write the JSON text to the stream. You need to choose an encoding - I would suggest UTF-8. So for example:

JSONObject json = new JSONObject();
json.put("type", "CONNECT");
Socket s = new Socket("192.168.0.100", 7777);
try (OutputStreamWriter out = new OutputStreamWriter(
        s.getOutputStream(), StandardCharsets.UTF_8)) {
    out.write(json.toString());
}

people

See more on this question at Stackoverflow