【发布时间】:2013-09-05 08:58:14
【问题描述】:
我有一个套接字服务器正在运行,它将为客户端发出 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;
提前致谢,
卡亚
【问题讨论】:
-
请发布您的服务器发出的 json 字符串。如果可能,请发布您的代码
-
@Prateek 我已经更新了我的问题以包含我从服务器获得的示例 json 字符串和我尝试过的代码。
标签: java json parsing sockets stream