无法从JSON对象获取特定数据

时间:2013-10-29 10:53:42

标签: java json

我正在尝试使用org.json.JSONObject库从json响应中提取特定数据 Heres是我的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"));


} 

无论如何,我只能提取DuObjects的名称字段吗?

3 个答案:

答案 0 :(得分:1)

您可以使用

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

获取名称。

答案 1 :(得分:1)

1:您的完整回复是JSON OBJECT

2:如果任何元素写成

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

这是一个JSON对象

3:如果任何元素被写成

 "some key name " :  " some value " 

这是你可以通过

得到的json对象里面的值
jsonObject.getString("key name")

4:如果任何元素被写成

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

然后这是一个JSON数组,您必须将其带入JSON ARRAY,然后通过

遍历其元素
jsonObject.getJSONARRAY("key name for JSON ARRAY IN RESPONSE ")

然后你可以通过

遍历JSON ARRAY的元素
`jsonArrayObj.get(0);`

答案 2 :(得分:0)

您可以使用Jackson库转换为java。 Jackson api提供注释级别,它会自动将json转换为pojo对象,并将对象转换为json,反之亦然。请参阅此链接。你可以很好地了解这个

http://wiki.fasterxml.com/JacksonSampleSimplePojoMapper

http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/