我正在尝试从字符串中读取JSON(从Web获取),但它返回null
。
具体来说,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字符串:
{
"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!
答案 0 :(得分:0)
试试这个:
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(datJ);
JSONObject jsonObject = (JSONObject) obj;
JSONObject rikeardObject = (JSONObject) jsonObject.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();
}
答案 1 :(得分:0)
使用这种方法对我有用,
private void extractJson(){
String jsonString="{\"rikeard\":{\"id\":2828822,\"name\":\"Rikeard\",\"profileIconId\":688,\"summonerLevel\":30,\"revisionDate\":1422917445000}}";
try {
JSONObject jsonObject=new JSONObject(jsonString);
if(jsonObject!=null){
jsonObject=jsonObject.optJSONObject("rikeard");
if(jsonObject!=null){
String id=jsonObject.optString("id");
Log.d("MainActivity","id="+id);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
答案 2 :(得分:0)
“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();
}