我有一个正在运行的套接字服务器,它将为客户端发出 json 字符串。我尝试使用 json-simple 来解析它们。但是,我面临的问题是,服务器没有任何分隔符来分隔 json 字符串。所以,我的 json-simple JSONParser 抛出 ParseException。
作为替代方案,我尝试使用 json-smart。但是,在这种情况下,JSONParser 只返回第一个对象并忽略字符串的其余部分。
我是这个 json 解析东西的新手。如果人们可以指导我正确处理 json 字符串流,那就太好了。
编辑: - 添加 JSON 字符串和示例代码
{"type":"response","id":"1","result":[true,0]}{"type":"response","id":"2","result":[true,1]}
目前,当我使用 json-smart 时,此方法返回单个对象,使用 json-simple 时返回 null。
public JSONObject getResponse(JSONObject request) {
String s = null;
Socket soc = null;
PrintWriter sout = null;
BufferedReader sin = null;
try {
soc = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
sout = new PrintWriter(soc.getOutputStream());
sin = new BufferedReader(
new InputStreamReader(soc.getInputStream()));
sout.println(request.toJSONString());
sout.flush();
s = sin.readLine();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
sin.close();
sout.close();
soc.close();
} catch (Exception e) {
}
}
Object response = null;
try {
response = JSONValue.parseWithException(s.toString());
}catch (ParseException e){
e.printStackTrace();
}
return (JSONObject) response;
提前致谢,
卡亚