shilpa navale
shilpa navale

Reputation: 509

How to retrive nested json array in flutter?

This is my JSON data:

{ 
   "result":"0",
   "school_code":"School Code",
   "dashboard":{ 
      "resultPrivilege":"0",
      "privilege":[ 
         { 
            "activity_id":"activity_id",
            "privilege_id":"privilege_id"
         }
      ]
   }
}

I want to retrieve privilege array from this Json data.
Print privilege array on terminal.
How to retrieve JSON object of privilege array

This is my code to retrieve JSON data:

var data = json.decode(response.body);
    var resultCheck = data['result'];
    if (resultCheck == '0') {
      var rest = data["dashboard"];
      debugPrint(rest);
}

output of this code:

result check 0
I/flutter (18905): {"privilege":[
{"activity_id":165,"privilege_id":1568}

I want to output this format when i print privilege:

I/flutter (18905):[{"activity_id":165,"privilege_id":1568}]

How to get only privilege array on terminal also how to print object of privilege?.

Upvotes: 0

Views: 2382

Answers (3)

Crazy Lazy Cat
Crazy Lazy Cat

Reputation: 15103

Try this,

Map<String, dynamic> jsonBody = json.decode(response.body);

String result = jsonBody["result"];
if (result == '0') {
  Map<String, dynamic> dashboard = jsonBody["dashboard"];
  List privilege = dashboard["privilege"];
  debugPrint(privilege.toString());
}

or you can easily create PODO(Plain Old Dart Objects) classes using quicktype or JsonToDart online tools. Then you can convert JSON to dart class objects.

Upvotes: 0

rstrelba
rstrelba

Reputation: 1964

import 'dart:convert';

void main() {
  var jsonData='{"result":"0","school_code":"School Code","dashboard":{"resultPrivilege":"0", "privilege": [{"activity_id":"activity_id","privilege_id":"privilege_id"}]}}';
  var json=jsonDecode(jsonData);
  json['dashboard']['privilege'].forEach((obj){
    //
    print(obj.toString());
  });
}

Upvotes: 1

Naveen Avidi
Naveen Avidi

Reputation: 3073

Map previlege = {
    'result': '0',
    'school_code': 'School Code',
    'dashboard': {
      'resultPrivilege': '0',
      'privilege': [
        {
          'activity_id': 'activity_id',
          'privilege_id': 'privilege_id',
        }
      ],
    }
  };
  print('Reuslt:  ${previlege['result']}' +
      '\nSchool Code:  ${previlege['school_code']}' +
      '\nActivity ID:  ${previlege['dashboard']['privilege'][0]['activity_id']}');

Screenshot

Upvotes: 1

Related Questions