-2

my json string is here

{
"user": {"id": "S5675","name": "soman"},
 "main": {"class1": { "modules": ["1","2"],
 "subjects": { "english": {"type": "english","module_id": "1"},
 "hindi": {"type": "hindi", "module_id": "2",}}},
  "class2": {"modules": ["2","3"],
"subjects": {"english": {"type": "english","module_id": "2"},
  "hindi": {"type": "urdu", "module_id": "3",}}}}}

I want to extract class1,class2 and its corresponding subjects . Here for class1 - english and hindi. and for class2 - english and urdu. I have tried like below

 JSONObject subObj = json.getJSONObject("main"); //get class1 and class2      
    Iterator<String> keys=subObj.keys();
    while(keys.hasNext()){
    String key=keys.next();
    Log.i("key","" + key);
    }

I get class1 and class2. But how to extract corresponding subjects from above json. please suggest

Dhanya Santhosh
  • 101
  • 1
  • 17

1 Answers1

3

They're all JSONObjects, so extract them as such

JSONObject subObj = json.getJSONObject("main"); //get class1 and class2      
JSONObject class1 = subObj.getJSONObject("class1");
JSONObject subjects= class1.getJSONObject("subjects");
JSONObject english= subjects.getJSONObject("english");
// Get the values
String type = english.getString("type");
int moduleId = english.getInt("module_id");

JSONObject hindi= subjects.getJSONObject("hindi");
...

Now go inside hindi in the same way and extract the values. Do the same for class2.

Bidhan
  • 10,607
  • 3
  • 39
  • 50