1

I want to read this JSON file in Android using json simple library.

My JSON file looks like this:

[  
    {  
        "name":"John",
        "city":"Berlin",
        "cars":[  
            "audi",
            "bmw"
        ],
        "job":"Teacher"
    },
    {  
        "name":"Mark",
        "city":"Oslo",
        "cars":[  
            "VW",
            "Toyata"
        ],
        "job":"Doctor"
    }
]
Pang
  • 9,564
  • 146
  • 81
  • 122
Prakash M
  • 111
  • 1
  • 1
  • 12

2 Answers2

1

This may help you,

  import org.json.simple.JSONArray;
  import org.json.simple.JSONObject;
  import org.json.simple.parser.JSONParser;

  JSONParser parser=new JSONParser();
      String s = "[{\"name\":\"John\",\"city\":\"Berlin\",\"cars\":[\"audi\",\"bmw\"],\"job\":\"Teacher\"},{\"name\":\"Mark\",\"city\":\"Oslo\",\"cars\":[\"VW\",\"Toyata\"],\"job\":\"Doctor\"}]";
      try{
         Object obj = parser.parse(s);
         JSONArray array = (JSONArray)obj;
         for (int i=0;i<array.size();i++){
             JSONObject jsonObj=(JSONObject) array.get(i);
             System.out.println(jsonObj.get("name"));
             System.out.println(jsonObj.get("city")); 
             JSONArray cars=(JSONArray) jsonObj.get("cars");
             for(int j=0;j<cars.size();j++){
                 System.out.println(cars.get(j));
             }
         }
      }catch(Exception e){
          e.printStackTrace();
      }
Boopathi
  • 226
  • 1
  • 4
  • 18
0

You could use GSON library by google found here:

An example of using this library in your case would be having a class called "Person" with certain fields that match the JSON:

Public class Person {
    private String name;
    private String city;
    private String[] cars;
    private String job;
}

You go from JSON to object by doing this:

Gson gson = new Gson();
Person p = gson.fromJson(jsonString, Person.class);
orrett3
  • 1,038
  • 1
  • 9
  • 15