Java org.json.JSONArray get from JSONObject

Description

Java org.json.JSONArray get from JSONObject


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject; 
 
public class Main { 
   private final static String  jString = "{"  
   + "    \"geodata\":  ["  
   + "        {"  
   + "                \"id\": \"1\","  
   + "                \"name\": \"CSS\","                   
   + "                \"gender\"  : \"female\","  
   + "                \"latitude\"  : \"37\","  
   + "                \"longitude\"  : \"-12\""             
   + "                }"  
   + "        },"  
   + "        {"  
   + "                \"id\": \"2\","  
   + "                \"name\": \"HTML\","           
   + "                \"gender\"  : \"male\","  
   + "                \"latitude\"  : \"37\","  
   + "                \"longitude\"  : \"-121\""             
   + "                }"  
   + "        }"  
   + "    ]"  //  www. ja  va  2  s.c o m
   + "}";  

   public static void main(String[] args) throws JSONException { 
       final JSONObject obj = new JSONObject(jString); 
       final JSONArray geodata = obj.getJSONArray("geodata"); 
       final int n = geodata.length(); 
       for (int i = 0; i < n; ++i) { 
         final JSONObject person = geodata.getJSONObject(i); 
         System.out.println(person.getInt("id")); 
         System.out.println(person.getString("name")); 
         System.out.println(person.getString("gender")); 
         System.out.println(person.getDouble("latitude")); 
         System.out.println(person.getDouble("longitude")); 
       }            
   } 
} 



PreviousNext

Related