【问题标题】:Java read JSON input streamJava 读取 JSON 输入流
【发布时间】:2014-12-04 17:42:25
【问题描述】:

我正在用 Java 编写一个简单的 TCP 服务器,它正在侦听某个端口上的某个 URL。一些客户端(不是 Java)向服务器发送 JSON 消息,类似于 {'message':'hello world!', 'test':555}。我接受消息并尝试获取 JSON(我正在考虑使用 GSON 库)。

Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();

但是我怎样才能从输入流中获取消息呢?我尝试使用ObjectInputStream,但据我了解,它等待序列化数据并且 JSON 没有序列化。

【问题讨论】:

  • JSON 是一个字符串,直到您使用库将其解码为 java 对象

标签: java json tcp inputstream


【解决方案1】:

BufferedReader 包装它并开始从中读取数据:

StringBuilder sb = new StringBuilder();
try (BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
    String line;
    while ( (line = br.readLine()) != null) {
        sb.append(line).append(System.lineSeparator());
    }
    String content = sb.toString();
    //as example, you can see the content in console output
    System.out.println(content);
}

将其作为字符串后,使用 Gson 或 Jackson 之类的库对其进行解析。

【讨论】:

  • 我觉得您的代码可能会引入部分读取或单次读取多条消息的问题。你能验证一下吗
【解决方案2】:
        StringBuffer buffer = new StringBuffer();
        int ch;
        boolean run = true;
        try {
            while(run) {
                ch = reader.read();
                if(ch == -1) { break; }
                buffer.append((char) ch);
                if(isJSONValid(buffer.toString())){ run = false;}
            }
        } catch (SocketTimeoutException e) {
            //handle exception
        }



private boolean isJSONValid(String test) {
        try {
            new JSONObject(test);
        } catch (JSONException ex) {
            try {
                new JSONArray(test);
            } catch (JSONException ex1) {
                return false;
            }
        }

        return true;
    }

【讨论】:

    猜你喜欢
    • 2019-07-15
    • 2011-05-29
    • 2014-10-03
    • 1970-01-01
    • 1970-01-01
    • 2012-03-12
    • 2012-02-26
    • 1970-01-01
    • 2023-04-04
    相关资源
    最近更新 更多