0

我正在检索 JSON 数据并将其存储在数组中以供使用。

我通过以下方式获取 json 数据:-

Uri uri = new Uri.Builder().scheme("http").authority().path().build();
     System.out.println("uri of category is : -"+uri);
     URI u = new URI(uri.toString());

     HttpClient httpclient = new DefaultHttpClient();
     HttpGet httpget = new HttpGet(u);
     HttpResponse response = httpclient.execute(httpget);
     HttpEntity entity = response.getEntity();
     is = entity.getContent();

     BufferedReader reader = new BufferedReader(new InputStreamReader(is),8);
     sb = new StringBuilder();
     sb.append(reader.readLine() + "\n");
     String line="0";
     while ((line = reader.readLine()) != null) {
              sb.append(line + "\n");
     }
     is.close();
     result=sb.toString(); 

但我的 json 是其他类型。所以我很困惑如何获取和存储在我的数组列表中。

{
employee: [
{
name: "ajay",
id: 1,
},
{
name: "rajiv",
id: 2,

}
],
address: [ 
{
city: "bombay",
pin: 114141 
}
]
}

我知道有第一个 JSONObject 并且有两个 jsonarray。但我怎样才能找回它。

4

3 回答 3

1
JSONArray jsonArray = jObject.getJSONArray("employee");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                modelJSon.setname(jsonObject.getString("name"));
                modelJSon.setid(jsonObject.getString("id"));
                modelList.add(modelJSon);
                modelJSon = new ModelBroker();
            }

JSONArray jsonArray = jObject.getJSONArray("address");
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    modelJSon.setcity(jsonObject.getString("city"));
                    modelJSon.setpin(jsonObject.getString("pin"));
                    modelList.add(modelJSon);
                    modelJSon = new ModelBroker();
                }
于 2013-09-17T11:20:03.527 回答
0

你可以用这个

JSONObject jObject = new JSONObject(jsonString);
JSONArray jArray = jObject.getJSONArray("employee");
JSONObject jo;
for(int i=0;i<jArray.length();i++){
    jo = jArray.getJSONObject(i);
    Log.d("name", jo.getString("name"));
    Log.d("id", jo.getString("id"));
}
jArray = jObject.getJSONArray("address");
for(int i=0;i<jArray.length();i++){
    jo = jArray.getJSONObject(i);
    Log.d("city", jo.getString("city"));
    Log.d("pin", jo.getString("pin"));
}
于 2013-09-17T11:21:52.857 回答
0
JSONObject json = new JSONObject(String jsonString);
JSONArray employeesArray = json.getJSONArray("employee");

final int arrayLength = employeesArray.length();
  for (int i = 0; i< arrayLength; i++) {
    JSONObject employeeJson = array.getJSONObject(i);
    // parse employee JSON and add it to your ArrayList
  }

对另一个数组做同样的事情。

于 2013-09-17T11:14:02.140 回答