Sivashankar KS
Sivashankar KS

Reputation: 121

flutter problem in json parsing of dynamic key values

Following is the output of my JSON

{
    "success": true,
    "data": {
        "ones": [{
                "id": "2",
                "username": "LM10002"
            },
            {
                "id": "6",
                "username": "LM10006"
            }
        ],
        "twos": [{
                "id": "3",
                "username": "LM10003"
            },
            {
                "id": "8",
                "username": "LM10008"
            }
        ],
        "threes": [{
            "id": "4",
            "username": "LM10004"
        }],
        "fours": [{
                "id": "5",
                "username": "LM10005"
            },
            {
                "id": "14",
                "username": "GT10014"
            }
        ]
    }
}

Here the keys ones, twos, threes, fours are dynamic key values I tried parsing and able to get the values of

  DownLineModel({this.success, this.data});
  DownLineModel.fromJson(Map<String, dynamic> json) {
    success = json['success'];
    data = json['data'];
    print(data);

how can i parse the json and find the key terms and again parse it.

Upvotes: 8

Views: 5504

Answers (4)

Sagar Acharya
Sagar Acharya

Reputation: 3777

Just check out the example that I have made for you based on the json that you provided.

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:json_parsing_example/models.dart';
import 'package:http/http.dart' as http;

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: HomePage());
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  double value;

  String json = '''
  {
    "success": true,
    "data": {
        "ones": [{
                "id": "2",
                "username": "LM10002"
            },
            {
                "id": "6",
                "username": "LM10006"
            }
        ],
        "twos": [{
                "id": "3",
                "username": "LM10003"
            },
            {
                "id": "8",
                "username": "LM10008"
            }
        ],
        "threes": [{
            "id": "4",
            "username": "LM10004"
        }],
        "fours": [{
                "id": "5",
                "username": "LM10005"
            },
            {
                "id": "14",
                "username": "GT10014"
            }
        ]
    }
}
  
  ''';
  @override
  void initState() {
    super.initState();

    getData();
  }

  getData() {
    Map mapValue = jsonDecode(json);
    // This is where you iterate via the data object
    // that is the value which is key,value pair
    List<Data> data = List();
    mapValue['data'].forEach((key, value) {
      List<User> user = List();
      value.forEach((item) {
        user.add(User(id: item['id'], username: item['username']));
      });
      data.add(Data(name: key, userList: user));
    });

    data.forEach((element) {
      print(element.name + " : " + '${element.userList.length}');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(child: Text('s')),
    );
  }
}

class Data {
  final String name;
  final List<User> userList;

  Data({this.name, this.userList});
}

class User {
  final String id;
  final String username;

  User({this.id, this.username});
}

Let me know if it works.

Upvotes: 6

Navaneeth P
Navaneeth P

Reputation: 1561

json['data'] will be Map<String, dynamic>. So you can iterate over those dynamic keys using forEach.

json['data'].forEach((dynamicKey, list) {
  // dynamicKey will be 'ones', 'twos', ....
  // list will be the corresponding list of maps
});

Upvotes: 2

Alok
Alok

Reputation: 9018

Assuming that when you do this print(data), you get this response

    {
        "ones": [{
                "id": "2",
                "username": "LM10002"
            },
            {
                "id": "6",
                "username": "LM10006"
            }
        ],
        "twos": [{
                "id": "3",
                "username": "LM10003"
            },
            {
                "id": "8",
                "username": "LM10008"
            }
        ],
        "threes": [{
            "id": "4",
            "username": "LM10004"
        }],
        "fours": [{
                "id": "5",
                "username": "LM10005"
            },
            {
                "id": "14",
                "username": "GT10014"
            }
        ]
    }

Now, what we can do is to, again iterate over the data, and find the dynamic keys like ones, twos....

We can do something like this. I am showing you for ones only, you can do for the res

//for ones
List<Map<String, String>> ones = data["ones"];

//iterating over it
ones.forEach((element){
   // we are now inside the array
   // iterating over element which is {"id": "", "username": ""}
   element.forEach((key, value){
      print("$key => $value");
   });
});

// OUTPUT
// id => 2
// username => LM10002
// id => 6
// username => LM10006

Upvotes: 0

chakibbaiker
chakibbaiker

Reputation: 123

Unless this.data is a Map<dynamic, dynamic> your code won't work. You have to create a separate class for the data property with its own DataModel.fromJson(Map json) method. And then in DownLineModel constructor you simple parse the data json like this:

this.data = DataModel.fromJson(jsonData);

Upvotes: 2

Related Questions