grc
grc

Reputation: 324

Flutter json decode returns null

I'm getting a null return when I run the following code. Apparently I'm not accessing json correctly.

Is there another way to access json data? Or is it ok to use it like that?

Future Class - parsing json from a url

  Future<List<User>> _getUsers() async {

    var data = await http.get("https://...api.php");


    if (data.statusCode == 200) {

        print('Status Code 200: Ok!');

        var jsonData = json.decode(data.body);


        List<User> users = [];

        for (var u in jsonData[0]) {


          print(u[0]["title"]);
          User user = User(u["id"], u["source"], u["desc"], u["link"], u["title"]);

          users.add(user);

        }

        print(users.length);

        return users;

    } else {

      throw Exception('Failed to load json');

    }


  }

Class

class User {

  final int id;
  final String source;
  final String desc;
  final String link;
  final String title;

  User(this.id, this.source, this.desc, this.link, this.title);


}

Basic json structure:

{
    "0":{
        "id":0,
        "source":"XXX",
        "link":"XXXX",
        "title":"XXXX",
        "desc":"XXXX"
    },
    "1":{
        "id":1,
        "source":"XXX",
        "link":"XXXX",
        "title":"XXXX",
        "desc":"XXXX"
    }
}

What am missing here? thanks.

Upvotes: 0

Views: 1266

Answers (2)

Zeynal
Zeynal

Reputation: 132

Your json structure is not a real json. But if your json is like this:

{
    "0":{
        "id":0,
        "source":"XXX",
        "link":"XXXX",
        "title":"XXXX",
        "desc":"XXXX"
    },
    "1":{
        "id":1,
        "source":"XXX",
        "link":"XXXX",
        "title":"XXXX",
        "desc":"XXXX"
    }
}

You can get data like this:

for (int i = 0; i < length; i ++) {   
      User user = User(u["$i"]["id"], u["$i"]["source"], u["$i"]["desc"], u["$i"]["link"], u["$i"]["title"]);

      users.add(user);
}

Upvotes: 1

Daniel Figueroa
Daniel Figueroa

Reputation: 10666

You're trying to use something that isn't a list as a list. The json structure you've provided looks like part of an object and not a list.

A list would look like this:

[{
    "id": 0,
    "source": "XXX",
    "link": "XXXX",
    "title": "XXXX",
    "desc": "XXXX"
}]

But since the underlying structure is a Map you could iterate over the keys, doing something like this:

for (var k in jsonData.keys) {
    var u = jsonData[k];
    print(u["title"]);
    User user = User(u["id"], u["source"], u["desc"], u["link"], u["title"]);
}

Upvotes: 1

Related Questions