如何通过java套接字发送Json对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21953958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 11:36:59  来源:igfitidea点击:

How to send Json object through java sockets?

javajsonsocketsobjectoutputstream

提问by user3339626

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

你如何通过套接字发送 Json 对象,最好通过 Java 中的 ObjectOutputStream 类,这是我到目前为止所得到的

    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?

但这给了 java.io.streamcorruptedexception 异常有什么建议吗?

回答by Jon Skeet

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

ObjectOutputStream您应该创建一个OutputStreamWriter,而不是使用,然后使用它来将JSON 文本写入流。您需要选择一种编码 - 我建议使用 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());
}