通过http请求获取嵌套Json返回null

Anis Benna:

我有一个要尝试获取的json api。但是,嵌套的“ studentInscription”值始终为空。其他值可以正确获取并可以访问。

[
  {
    "studentId": 10,
    "studentName": "John Doe",
    "studentInscription": {
      "inscriptionId": 15,
      "inscriptionPrice": 905.25
    }
  },
  {
    "studentId": 12,
    "studentName": "Steve Doe",
    "studentInscription": {
      "inscriptionId": 18,
      "inscriptionPrice": 905.25
    }
  }
]

这是GET代码:

Future<List<Student>> getStudents() async {
    try {
      Response res = await get(apiURL);
      if (res.statusCode == 200) {
        // Successfull get request
        List<dynamic> body = jsonDecode(res.body);
        List<Student> students = body
            .map(
              (dynamic item) => Student.fromJson(item),
            )
            .toList();
        return students;
    } catch (e) {
      print("Could not fetch");
      return null;
    }
  }

学生模型如下:

import '.../inscription.dart';

class Student{
  int id;
  String name;
  Inscription inscription;

  Student({this.id, this.name, this.inscription});
 
  factory Student.fromJson(Map<String, dynamic> json) {
    return Student(
      id: json['studentId'] as int,
      name: json['studentName'],
      inscription: json['studentInscription'] as Inscription,           // null data
      // inscription: Inscription.fromJson(json['studentInscription']), // tried this but no luck
    );
  }
}

铭文模型如下:

class Inscription {
  int id;
  double price;

  Inscription({this.id, this.price});

  factory Inscription.fromJson(Map<String, dynamic> json) {
    return Inscription(
      id: json['inscriptionId'] as int,
      price: json['inscriptionPrice'] as double,
    );
  }
}

我最终希望能够做到这一点:

myList [0] .inscription.price

我可以做到这一点而没有问题:

myList [0] .studentName

编辑,这是我使用请求的代码:

Future<List<Student>> futureStudents = getStudents();

return Container(
  child: FutureBuilder(
    future: futureStudents,
    builder: (context, snapshot) {
      if (snapshot.hasData) {
        print(snapshot.data[0].name); // This has a value
        print(snapshot.data[0].inscription); // This is null
        return _buildListView(snapshot.data);
      }
    }
  )
);
Shri Hari:

我认为您错过了Student的构造函数
试试这个

class Student{
  int id;
  String name;
  Inscription inscription;
 
  // Constructor
  Student({this.id, this.name, this.inscription});
  
  factory Student.fromJson(Map<String, dynamic> json) {
    return Student(
      id: json['studentId'],
      name: json['studentName'],
      inscription: Inscription.fromJson(json['studentInscription']),            
    );
  }
}

希望行得通!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章