无法解析类型'String'不是'index'类型'int'的子类型

时间:2020-02-27 10:34:41

标签: json flutter dart

我最近开始遇到问题。我需要将我的json response解析为模型对象类的list,但我不断收到此错误:

type 'String' is not a subtype of type 'int' of 'index'

在线尝试了几种解决方案,但对我不起作用。我很想知道我在模型类中的变量声明是问题,所以我将它们更改为动态,但仍然对我不起作用。

标题

模型

class MenteeIndex {
  dynamic id;
  dynamic mentor_id;
  dynamic mentee_id;
  dynamic status;
  dynamic session_count;
  dynamic current_job;
  dynamic email;
  dynamic phone_call;
  dynamic video_call;
  dynamic face_to_face;
  dynamic created_at;
  dynamic updated_at;

  MenteeIndex(this.id, this.mentor_id, this.mentee_id, this.status, this.session_count, this.current_job,
      this.email, this.phone_call, this.video_call, this.face_to_face, this.created_at, this.updated_at);

  Map<String, dynamic> toJson() => {
    'id': id,
    'mentor_id': mentor_id,
    'mentee_id': mentee_id,
    'status': status,
    'session_count': session_count,
    'current_job': current_job,
    'email':email,
    'phone_call': phone_call,
    'video_call': video_call,
    'face_to_face': face_to_face,
    'created_at': created_at,
    'updated_at': updated_at,
  };

  MenteeIndex.fromJson(Map<String, dynamic> json):
        id = json['id'],
        mentor_id = json['mentor_id'],
        mentee_id = json['mentee_id'],
        status = json['status'],
        session_count = json['session_count'],
        current_job = json['current_job'],
        email = json['email'],
        phone_call = json['phone_call'],
        video_call = json['video_call'],
        face_to_face = json['face_to_face'],
        created_at = json['created_at'],
        updated_at = json['updated_at'];
}

主要

 Future fetchIndex() async {
        SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
        var uri = NetworkUtils.host + AuthUtils.endPointIndex;
        try {
          final response = await http.get(
            uri,
            headers: {'Accept': 'application/json', 'Content-Type': 'application/json','Authorization': 'Bearer ' + sharedPreferences.get("token"), },
          );
          var encodeFirst = json.encode(response.body);
          final responseJson = json.decode(encodeFirst);
    //here is where the error is
          for (var u in responseJson["data"]) {
            MenteeIndex user = MenteeIndex(
                u["id"],
                u["mentor_id"],
                u["mentee_id"],
                u["status"],
                u["session_count"],
                u["current_job"],
                u["email"],
                u["phone_call"],
                u["video_call"],
                u["face_to_face"],
                u["created_at"],
                u["updated_at"]);

            menteeIndexes.add(user);
            setState((){
               mentorIdList = menteeIndexes.map((MenteeIndex) => MenteeIndex.mentor_id);
              indexIds = menteeIndexes.map((MenteeIndex) => MenteeIndex.id);
              status = menteeIndexes.map((MenteeIndex) => MenteeIndex.status);
            });
          }
          return responseJson;
        } catch (exception) {
          print(exception);
        }
          }

响应/错误

 {"current_page":1,"data":[{"id":13,"mentor_id":"5","mentee_id":"184","status":null,"session_count":0,"current_job":null,"email":null,"phone_call":null,"video_call":null,"face_to_face":null,"created_at":"2020-02-20 20:37:50","updated_at":"2020-02-20 20:37:50"},{"id":14,"mentor_id":"8","mentee_id":"184","status":null,"session_count":0,"current_job":null,"email":null,"phone_call":null,"video_call":null,"face_to_face":null,"created_at":"2020-02-21 22:39:31","updated_at":"2020-02-21 22:39:31"},{"id":15,"mentor_id":"10","mentee_id":"184","status":null,"session_count":0,"current_job":null,"email":null,"phone_call":null,"video_call":null,"face_to_face":null,"created_at":"2020-02-23 05:15:23","updated_at":"2020-02-23 05:15:23"},{"id":16,"mentor_id":"191","mentee_id":"184","status":null,"session_count":0,"current_job":null,"email":null,"phone_call":null,"video_call":null,"face_to_face":null,"created_at":"2020-02-23 05:17:34","updated_at":"2020-02-23 05:17:34"},{"id":17,"mentor_id":"141","mentee_id":"184","status":"1",
I/flutter (20995): type 'String' is not a subtype of type 'int' of 'index'

2 个答案:

答案 0 :(得分:0)

将响应正文解码为Map

final responseJson = json.decode(response.body);

Map列表转换为MenteeIndex列表

  final menteeIndexes = responseJson["data"].map(
        (json) => MenteeIndex.fromJson(json)
      ).toList();

答案 1 :(得分:0)

查看此模型课程

// To parse this JSON data, do
//
//     final yourModel = yourModelFromJson(jsonString);

import 'dart:convert';

YourModel yourModelFromJson(String str) => YourModel.fromJson(json.decode(str));

String yourModelToJson(YourModel data) => json.encode(data.toJson());

class YourModel {
    int currentPage;
    List<Datum> data;

    YourModel({
        this.currentPage,
        this.data,
    });

    factory YourModel.fromJson(Map<String, dynamic> json) => YourModel(
        currentPage: json["current_page"],
        data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "current_page": currentPage,
        "data": List<dynamic>.from(data.map((x) => x.toJson())),
    };
}

class Datum {
    int id;
    String mentorId;
    String menteeId;
    dynamic status;
    int sessionCount;
    dynamic currentJob;
    dynamic email;
    dynamic phoneCall;
    dynamic videoCall;
    dynamic faceToFace;
    DateTime createdAt;
    DateTime updatedAt;

    Datum({
        this.id,
        this.mentorId,
        this.menteeId,
        this.status,
        this.sessionCount,
        this.currentJob,
        this.email,
        this.phoneCall,
        this.videoCall,
        this.faceToFace,
        this.createdAt,
        this.updatedAt,
    });

    factory Datum.fromJson(Map<String, dynamic> json) => Datum(
        id: json["id"],
        mentorId: json["mentor_id"],
        menteeId: json["mentee_id"],
        status: json["status"],
        sessionCount: json["session_count"],
        currentJob: json["current_job"],
        email: json["email"],
        phoneCall: json["phone_call"],
        videoCall: json["video_call"],
        faceToFace: json["face_to_face"],
        createdAt: DateTime.parse(json["created_at"]),
        updatedAt: DateTime.parse(json["updated_at"]),
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "mentor_id": mentorId,
        "mentee_id": menteeId,
        "status": status,
        "session_count": sessionCount,
        "current_job": currentJob,
        "email": email,
        "phone_call": phoneCall,
        "video_call": videoCall,
        "face_to_face": faceToFace,
        "created_at": createdAt.toIso8601String(),
        "updated_at": updatedAt.toIso8601String(),
    };
}

只需将您的response.body插入此方法:

 final yourModel = yourModelFromJson(response.body);

您只需使用下面的调用即可获取数据列表:

List<Datum> dataList = List();

dataList = yourModel.data;

在这里您可以获得数据列表

您将从中获取Single对象,然后根据您的需要执行任何操作。

相关问题