How to send Json object through java sockets?

user3339626 picture user3339626 · Feb 22, 2014 · Viewed 34.5k times · Source

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?

Answer

Jon Skeet picture Jon Skeet · Feb 22, 2014

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