我正在尝试从字符串(从Web获取)中读取JSON,但返回null。
null
具体来说,result.append(name + id);给我nullnull
result.append(name + id);
nullnull
JSONParser parser = new JSONParser(); try { Object obj = parser.parse(datJ); JSONObject jsonObject = (JSONObject) obj; String name = (String) jsonObject.get("name"); Integer id = (Integer) jsonObject.get("id"); result.append(name + id); } catch (MalformedURLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (org.json.simple.parser.ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); }
考虑datJ包含以下JSON字符串:
datJ
{ "rikeard":{ "id":2828822, "name":"Rikeard", "profileIconId":688, "summonerLevel":30, "revisionDate":1422917445000 } }
编辑:最终代码工作
JSONParser parser = new JSONParser(); try { String datJ = IOUtils.toString(new URL(url)); Object obj = parser.parse(datJ); JSONObject rikeardObject = (JSONObject) ((Map<?, ?>) obj).get("rikeard"); String name = (String) rikeardObject.get("name"); Long id = (Long) rikeardObject.get("id");
特别感谢Sufian和Ved!
“ id”和“ name”位于JSON对象内部,键为“ rikeard”。因此,您需要进行如下更改:
JSONParser parser = new JSONParser(); try { Object obj = parser.parse(datJ); JSONObject jsonObject = (JSONObject) obj; JSONObject rikeardObject = (JSONObject) obj.get("rikeard"); String name = (String) rikeardObject.get("name"); Integer id = (Integer) rikeardObject.get("id"); result.append(name + id); } catch (MalformedURLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (org.json.simple.parser.ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); }