2013-04-24 170 views
1

我需要分析一些JSON对象,whihc看起来是这样的:JSON对象解析

{"searchdata":{},"userdata":{"currency":"69","notificationCount":7}} 

我用下面的代码来实现这一目标:

JSONObject rootObj = new JSONObject(getResponse); 
JSONObject jSearchData = rootObj.getJSONObject("searchdata"); 
JSONObject userData = jSearchData.getJSONObject("userdata"); 

String currency = userData.getString("currency"); 

我不能打印currency对象来自上面的代码。我不断收到异常:

Exception: org.json.JSONException: No value for userdata 

我不知道我在做什么错。

任何形式的帮助将不胜感激。

+0

痛苦少):https://sites.google .com/site/gson/gson-user-guide#TOC-Using-Gson – MemLeak 2013-04-24 08:30:21

回答

10
JSONObject rootObj = new JSONObject(getResponse); 

userData里面rootObj内部没有searchdata

为空值,你应该使用:

isNull 

if (!rootObj.isNull("userdata")) { 
    JSONObject userData = rootObj.getJSONObject("userdata"); 
} 
+0

谢谢,但是如何处理来自服务器的空响应。像这个'{“searchdata”:{},“userdata”:null}'。每当我从服务器得到空响应时,我得到这个异常:'异常:org.json.JSONException:在org.json.JSONObject $ 1类型的userdata上的值null不能转换为JSONObject',因为我的PostExecute()方法是给出零响应。 – Anupam 2013-04-24 08:34:26

+0

看到我的编辑.... – Blackbelt 2013-04-24 08:36:27

+0

这不是帮助我,不断得到'异常:org.json.JSONException:值为null ord.json.JSONObject $ 1的用户数据无法转换为JSONObject',如果值为空。当然 – Anupam 2013-04-24 08:56:10

1

使用

JSONObject userData = rootObj.getJSONObject("userdata"); 

得到currency

currency = userData.getString("currency"); 

使用这样的方式......

检查对象为空..

按黑带@的答案用途:if (!rootObj.isNull("userdata"))

+0

谢谢,但如何处理来自服务器的空响应,例如'{“searchdata”:{},“userdata”:null}' – Anupam 2013-04-24 08:31:20

+0

我在应用更改后总是收到此错误。 '异常:org.json.JSONException:类型为org.json.JSONObject $ 1的userdata的值为null无法转换为JSONObject' – Anupam 2013-04-24 08:44:10