[英]Java read JSON input stream
我正在用 Java 編寫一個簡單的 TCP 服務器,它正在偵聽某個端口上的某個 URL。 某些客戶端(非 Java)向服務器發送 JSON 消息,類似於{'message':'hello world!', 'test':555}
。 我接受消息並嘗試獲取 JSON(我正在考慮使用 GSON 庫)。
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
但是如何從輸入流中獲取消息? 我嘗試使用ObjectInputStream
,但據我所知,它等待序列化數據,而 JSON 沒有序列化。
用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 這樣的庫來解析它。
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.