0

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.

2 Answers 2

1

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"]);
}
Sign up to request clarification or add additional context in comments.

1 Comment

It did work with that "for" loop. I wrongly disclosed json strcutrue, but it's exactly as you said. Thanks.
1

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.