NoSuchMethodError(NoSuchMethodError:方法“ []”在null上调用。接收方:null尝试调用:[](“ title”))

时间:2020-09-15 19:07:41

标签: json flutter

从json提取数据后出现此错误;

我的模型是这样的:

class JobModel {
 final String title;
 final int id;
 final String slug;
 final String content;

JobModel(this.title, this.id, this.slug, this.content);

JobModel.fromJson(Map<String, dynamic> json)
  : title = json['title'],
    id = json['id'],
    slug = json['slug'],
    content = json['content'];

}

这是我从json文件中获取数据的功能:

List<JobModel> jobList;
Map<String, dynamic> jsonResponse;
Future<List<JobModel>> _getJobs() async {
var response = await http.get(
    "https://www.eradauti.ro/api/context?pathname=/anunturi/pagina-1&userID=");
this.setState(() {
  jsonResponse = json.decode(response.body);
});
jobList = List<JobModel>();
jsonResponse.forEach((key, value) {
  JobModel job = JobModel.fromJson(value);
  jobList.add(job);
});
print(jsonResponse[0]['title']); //shows null
return jobList;

}

我的json文件如下:

{
  "context": [
    // first JobModel Map
    {
      "title": "some title here",
      "id": 1234,
      "slug": "some slug value",
      "content": "the rest of the object content",
    },
    // second JobModel Map
    {
      "title": "some other title here",
      "id": 5678,
      "slug": "some other slug value",
      "content": "blah blah,",
    },
  ]
}

你能告诉我我做错了吗?

1 个答案:

答案 0 :(得分:0)

您的回复格式与您编码的格式不同。

结构是这样的:

{
"context": {
    "categories": [
        {
            "id": 15,
            "title": "Auto-Moto",
            "slug": "auto-moto",
            "content": "Vanzari-cumparari de automobile, piese acte. Anunţurile sunt destinate zonei Radauti-Suceava<br />",
            "related": {
                "link": "/anunturi/auto-moto-15",
                "archiveLink": "/arhiva-anunturi/c/auto-moto-15",
                "deletedPostCount": 387,
                "postCount": 22
            }
        },

因此,要进入作业列表,您应该进行相应的解析。进入工作清单的正确声明应为:

print(jsonResponse['context']['categories'])

要能够创建工作模型列表,请尝试以下操作:

var json = jsonResponse['context']['categories'];
var jobList = List<JobModel>();
json.forEach((key, value) {
  print(key);
  JobModel job = JobModel.fromJson(value);
  jobList.add(job);
});
print(jobList);

尝试以下代码段:

Future<List<JobModel>> _getJobs() async {
     var response = await http.get(
    "https://www.eradauti.ro/api/context?pathname=/anunturi/pagina-1&userID=");
     jsonResponse = json.decode(response.body);
     var json = jsonResponse['context']['categories'];
     var jobList = List<JobModel>();
     json.forEach((key, value) {
       print(key);
       JobModel job = JobModel.fromJson(value);
       jobList.add(job);
     });
     print(jobList);
}