0

I am retrieving JSON data and store it in array for using.

I get the json data by:-

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(); 

but my json is some other type. so i am confuse how to get and store in my arraylist.

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

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

I know that there is first JSONObject and having two jsonarray. but how can i retrive it.

user1629977
  • 437
  • 1
  • 5
  • 21

3 Answers3

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();
                }
dipali
  • 10,966
  • 5
  • 25
  • 51
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
  }

Do likewise with the other array.

Bartek Filipowicz
  • 1,235
  • 7
  • 9
0

You can use this

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"));
}
Sunil Mishra
  • 3,796
  • 1
  • 27
  • 40