2013-10-29 140 views
0

我試圖使用org.json.JSONObject庫 JSON響應提取特定的數據得到具體的數據繼承人是我的JSON響應:無法從JSON對象

{ 
"facets": { 
"application": [ 
    { 
    "name": "38", 
    "distribution": 1 
    } 
], 
"node": [ 
    { 
    "name": "frstlwardu03_05", 
    "distribution": 1 
    } 
], 
"area": [ 
    { 
    "name": "x", 
    "distribution": 1 
    } 
], 
"company": [ 
    { 
    "name": "war001", 
    "distribution": 1 
    } 
] 
}, 
"duObjects": [ 
{ 
    "id": "TASK|TSK(ZRM760J)(000)(ZRM760JU00)(000)|ZSRPSRM000", 
    "name": "TSK(ZRM760J)(000)(ZRM760JU00)(000)", 
    "mu": "ZSRPSRM000", 
    "label": "", 
    "session": "ZRM760J|000", 
    "sessionLabel": "SAP SRM Achats frais generaux execution", 
    "uprocHeader": "ZRM760JU00|000", 
    "uprocHeaderLabel": "Header for SRM760J", 
    "uprocHeaderType": "CL_INT", 
    "domain": "M", 
    "domainLabel": "", 
    "application": "38", 
    "applicationLabel": "magasin", 
    "highlightResult": { 
    "name": "name", 
    "word": "TSK" 
    } 
} 
], 
"totalCount": 1, 
"pageSize": 10, 
"pageCurrent": 1, 
"pageNb": 1 
} 

這裏是我使用的方法到URL調用轉換成一個JSONObject:

public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException  
{  
InputStream is = new URL(url).openStream(); 
try { 
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-  
8"))); 
    String jsonText = readAll(rd); 
    JSONObject json = new JSONObject(jsonText); 
    return json; 
} finally { 
    is.close(); 
} 
} 

當我把這種方法我能夠獲得在格蘭Duobject數據:

public static void main(String[] args) throws IOException, JSONException { 
JSONObject json = readJsonFromUrl("http://frstmwarwebsrv.orsyptst.com:9000/duobject?  
searchString=TSK(ZRM760J)(000)(ZRM760JU00) 
(000)&filterchecks=nameJob,nameWF,nameSWF,application,domain&p.index=0&p.size=10"); 
System.out.println(json.getJSONArray("duObjects")); 


} 

無論如何我只能提取DuObject的名稱字段嗎?

+0

遍歷JSON數組中的元素「轉換的URL調用一個JSONObject」,意味着你都可以從某些URL JSON的響應? – Jhanvi

回答

1

您可以使用

System.out.println(json.getJSONArray("duObjects").getJSONObject(0).getString("name")); 

得到的名稱。

1

1:您的完整的響應是一個JSON對象

2:如果任何元素是這樣寫

"some key name " : { " some value " } 

這是JSON對象

3:如果任何元件writen像

"some key name " : " some value " 

這是內部你值JSON對象,則可以通過

jsonObject.getString("key name") 

4得到:如果任何元件writen像

"some key name " : [ " some value " ] 

那麼這是一個JSON數組,你必須將它放入一個JSON數組中,然後遍歷它的元素

jsonObject.getJSONARRAY("key name for JSON ARRAY IN RESPONSE ") 

,然後你可以通過

`jsonArrayObj.get(0);`