N
N
nikesport2014-11-14 10:23:16
Java
nikesport, 2014-11-14 10:23:16

How to send JSON via ObjectOutStream ?

I want to send Json through socket here is the code:
Socket socket = new Socket(ipAddress, serverPort);
InputStream sin = socket.getInputStream();
OutputStream sout = socket.getOutputStream();
ObjectInputStream in = new ObjectInputStream(sin);
ObjectOutputStream out = new ObjectOutputStream(sout);
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("key","message");
jsonObject.addProperty("text","Hello world");
jsonObject.addProperty("ip_driver","ip892683740");
out.writeObject(jsonObject); .
Here is the handler code on the server side:
this socket = socket;
try {
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
objectInputStream = new ObjectInputStream(inputStream);
objectOutputStream = new ObjectOutputStream(outputStream);
} catch (IOException e) {
e.printStackTrace();
}
try {
jsonObject = (JsonObject) objectInputStream.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
JsonParser jsonParser = new JsonParser();
Object obj = jsonParser.parse(String.valueOf(jsonObject));
JsonObject jsonObj = (JsonObject)obj;
if (jsonObj.get("key").toString() == "message") {
new message(jsonObj.get("key").toString());
}
But nothing is transmitted, the debugger shows that ObjectOutStream = null
Can you tell me if it is necessary to serialize json if so, how? :)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Keyn Din, 2014-11-14
@Lure_of_Chaos

JSONObject is not Serializable, write and read as a string using the constructor and its write method.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question