如何通过java中的ObjectOutputStream类优先发送Json对象,这是我到目前为止所获得的
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);
但是这给了java.io.streamcorruptedexception异常任何建议吗?
答案 0 :(得分:15)
您应该创建一个ObjectOutputStream
,然后使用它将 JSON文本写入流中,而不是使用OutputStreamWriter
。你需要选择一种编码 - 我建议使用UTF-8。例如:
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());
}