将Foursquare HTTP响应转换为JSON的Java
-
25-10-2019 - |
题
在收到Foursquare的以下答复之后,当我尝试解析它时,我在下面收到错误:
回复:
{"meta":{"code":200},"response":{"venues":[{"id":"4b1c3ce9f964a520d60424e3","name":"Folsom Lake Bowl","contact":{},"location":{"address":"511 East Bidwell","lat":38.67291745,"lng":-121.165447,"distance":39,"postalCode":"95630","city":"Folsom","state":"CA"},"categories":[{"id":"4bf58dd8d48988d1e4931735","name":"Bowling Alley","pluralName":"Bowling Alleys","shortName":"Bowling Alley","icon":{"prefix":"https://foursquare.com/img/categories/arts_entertainment/bowling_","sizes":[32,44,64,88,256],"name":".png"},"primary":true}],"verified":false,"stats":{"checkinsCount":592,"usersCount":284,"tipCount":2},"hereNow":{"count":0}}]}}
错误:
Exception in thread "main" org.codehaus.jettison.json.JSONException: JSONObject["groups"] not found.
at org.codehaus.jettison.json.JSONObject.get(JSONObject.java:360)
at org.codehaus.jettison.json.JSONObject.getJSONArray(JSONObject.java:436)
at playaround.FoursquareAPI.get(FoursquareAPI.java:56)
at playaround.FoursquareAPI.main(FoursquareAPI.java:31)
代码:
StringBuilder sb = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
for (String line; null != (line = reader.readLine());) {
sb.append(line);
}
String output = sb.toString();
JSONObject json = new JSONObject(output);
JSONArray venues = json.getJSONObject("response").getJSONArray("groups").getJSONObject(0).getJSONArray("items");
System.out.println(venues.length());
我想要的就是阅读Java中的Jonobject的Foursquare的响应。有帮助吗?
解决方案
阅读堆栈痕迹,解析的JSON很好。
问题是您正在尝试阅读不存在的属性 - “群体”
其他提示
根据我的经验,如果您获得了JSON对象 - 例如我遇到的问题;解析返回的位置字段。我从以下代码开始:
JSONObject jsonObjLoc = new JSONObject(myLocation);
如果您可以获取对象,则只需参考“ hom hom”参数类似:
if(jsonObjLoc.has("myAddress")) { // name of field to look for
myTextAddress = jsonObjLoc.getString("address");
}
我使用必须防止未返回的空场或空字段。
不隶属于 StackOverflow