简体   繁体   English

Flutter model 用于嵌套 json object

[英]Flutter model for nested json object

I am new in Flutter.我是 Flutter 的新手。 I have tried to developed Model class in dart.我曾尝试在 dart 中开发 Model class。 but always show the error message但总是显示错误信息

Exception:type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String', tt:#0      new User.fromJson

I don't understand, where my code will error.我不明白,我的代码会在哪里出错。 I want to solutions.我想要解决方案。

I want to convert model class in dart.我想在 dart 中转换 model class。

[
    {
        "route": {
            "routeID": "aaaaaaaa",
            "routeTitle": "bbbbbbbb"
        },
        "distributor": {
            "distributorID": "cccccccccccc",
            "distributorName": "ddddddddddd"
        },
        "visitDate": null
    }
]

I have been tried to my source code.我已经尝试过我的源代码。 like below code像下面的代码

import 'dart:convert';

List<User> userFromJson(String str) =>
    List<User>.from(json.decode(str).map((x) => User.fromJson(x)));

String userToJson(List<User> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class User {
  User({
    this.visitDate,
    this.route,
    this.distributor,
  });

  String visitDate;
  String route;
  String distributor;

  factory User.fromJson(Map<String, dynamic> json) => User(
    visitDate: json["visitDate"],
    route: json["route"],
    distributor: json["distributor"],
  );

  Map<String, dynamic> toJson() => {
    "visitDate": visitDate,
    "route": route,
    "distributor": distributor,
  };
}

Route RouteFromJson(String str) => Route.fromJson(json.decode(str));

String RouteToJson(Route data) => json.encode(data.toJson());

class Route {
  Route({
    this.routeID,
    this.routeTitle,
  });

  String routeID;
  String routeTitle;

  factory Route.fromJson(Map<String, dynamic> json) => Route(
    routeID: json["routeID"],
    routeTitle: json["routeTitle"],
  );

  Map<String, dynamic> toJson() => {
    "routeID": routeID,
    "routeTitle": routeTitle,
  };
}
Distributor DistributorFromJson(String str) => Distributor.fromJson(json.decode(str));

String DistributorToJson(Distributor data) => json.encode(data.toJson());
class Distributor {
  Distributor({
    this.distributorID,
    this.distributorName,
  });

  String distributorID;
  String distributorName;

  factory Distributor.fromJson(Map<String, dynamic> json) => Distributor(
    distributorID: json["distributorID"],
    distributorName: json["distributorName"],
  );

  Map<String, dynamic> toJson() => {
    "distributorID": distributorID,
    "distributorName": distributorName,
  };
}

how to correct my model class.如何纠正我的 model class。 please help me.请帮我。 thanks谢谢

Change your User class like this:像这样更改您的用户 class :

 class User {
      User({
        this.visitDate,
        this.route,
        this.distributor,
      });
    
      String visitDate;
      Route route;
      Distributor distributor;
    
      factory User.fromJson(Map<String, dynamic> json) => User(
        visitDate: json["visitDate"],
        route = json['route'] != null ? Route.fromJson(json['route']) : null;
        distributor = json['distributor'] != null
            ? Distributor.fromJson(json['distributor'])
            : null;
      );
    
      Map<String, dynamic> toJson() => {
        "visitDate": visitDate,
        if (route != null) {
          data['route'] = this.route.toJson();
        }
        if (distributor != null) {
          data['distributor'] = this.distributor.toJson();
        }
      };
    }

You can also check out the json_serializable package for that.您还可以为此查看json_serializable package。 This way, you don't have to write this code yourself.这样,您不必自己编写此代码。

https://pub.dev/packages/json_serializable https://pub.dev/packages/json_serializable

This is how you can rewrite the model:这是重写 model 的方法:

import 'dart:convert';

List<User> usersFromJson(String str) =>
    List<User>.from(json.decode(str).map((x) => User.fromJson(x)));

String usersToJson(List<User> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class User {
  User({
    required this.visitDate,
    required this.route,
    required this.distributor,
  });

  String? visitDate;
  Route route;
  Distributor distributor;

  User.fromJson(Map<String, dynamic> json)
      : visitDate = json["visitDate"],
        route = Route.fromJson(json["route"]),
        distributor = Distributor.fromJson(json["distributor"]);

  Map<String, dynamic> toJson() => {
        "visitDate": visitDate,
        "route": route.toJson(),
        "distributor": distributor.toJson(),
      };
}

class Route {
  Route({
    required this.routeID,
    required this.routeTitle,
  });

  String routeID;
  String routeTitle;

  Route.fromJson(Map<String, dynamic> json)
      : routeID = json["routeID"],
        routeTitle = json["routeTitle"];

  Map<String, dynamic> toJson() => {
        "routeID": routeID,
        "routeTitle": routeTitle,
      };
}

class Distributor {
  Distributor({
    required this.distributorID,
    required this.distributorName,
  });

  String distributorID;
  String distributorName;

  Distributor.fromJson(Map<String, dynamic> json)
      : distributorID = json["distributorID"],
        distributorName = json["distributorName"];

  Map<String, dynamic> toJson() => {
        "distributorID": distributorID,
        "distributorName": distributorName,
      };
}

void main() {
  const data = '''[
    {
        "route": {
            "routeID": "aaaaaaaa",
            "routeTitle": "bbbbbbbb"
        },
        "distributor": {
            "distributorID": "cccccccccccc",
            "distributorName": "ddddddddddd"
        },
        "visitDate": null
    }
  ]''';
  final decoded = usersFromJson(data);
  final encoded = usersToJson(decoded);
  print(decoded);
  print(encoded);
}

Some things to note.有些事情要注意。

You appear to be using an outdated version of dart.您似乎使用的是过时版本的 dart。 I would suggest updating the version of dart in your project to 2.14.0 which is currently the latest major version.我建议将您项目中的2.14.0的版本更新为 2.14.0,这是当前最新的主要版本。 You might have to run flutter upgrade to do so.您可能必须运行flutter upgrade才能执行此操作。 You can change the version of dart in your pubspec.yaml file.您可以在pubspec.yaml文件中更改 dart 的版本。 The setting for your dart version will look something like this:您的 dart 版本的设置将如下所示:

environment:
  sdk: ">=2.14.0 <3.0.0"

The main problem you have in your code is that within your User class you have defined route and distributor to be of type String when really, you want them to be of type Route and Distributor .您在代码中遇到的主要问题是,在您的User class 中,您已将routedistributor定义为String类型,而实际上,您希望它们为RouteDistributor类型。 Within the constructor of your User class the expression json["route"] will return something like { "routeID": "aaaaaaaa", "routeTitle": "bbbbbbbb" } which is not a String but rather a Map<String, dynamic> which is why you are getting the error message above.在您的User class 的构造函数中,表达式json["route"]将返回类似{ "routeID": "aaaaaaaa", "routeTitle": "bbbbbbbb" }的东西,它不是String而是Map<String, dynamic>这就是您收到上述错误消息的原因。

Flutter Box.! Flutter 盒子!

You just need to do simple job is to visit following website.您只需要做简单的工作就是访问以下网站。 And need to put your response or map/list that you want to convert in model class and rest will be done by server.并且需要将您想要转换的响应或地图/列表放入 model class 和 rest 将由服务器完成。

By the way, For your List<Map<String, dynamic> data's model class is,顺便说一句,对于您的 List<Map<String, dynamic> 数据的 model class 是,

// To parse this JSON data, do
//
//     final routeModelClass = routeModelClassFromJson(jsonString);

import 'dart:convert';

List<RouteModelClass> routeModelClassFromJson(String str) => List<RouteModelClass>.from(json.decode(str).map((x) => RouteModelClass.fromJson(x)));

String routeModelClassToJson(List<RouteModelClass> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class RouteModelClass {
    RouteModelClass({
        this.route,
        this.distributor,
        this.visitDate,
    });

    Route route;
    Distributor distributor;
    dynamic visitDate;

    factory RouteModelClass.fromJson(Map<String, dynamic> json) => RouteModelClass(
        route: Route.fromJson(json["route"]),
        distributor: Distributor.fromJson(json["distributor"]),
        visitDate: json["visitDate"],
    );

    Map<String, dynamic> toJson() => {
        "route": route.toJson(),
        "distributor": distributor.toJson(),
        "visitDate": visitDate,
    };
}

class Distributor {
    Distributor({
        this.distributorId,
        this.distributorName,
    });

    String distributorId;
    String distributorName;

    factory Distributor.fromJson(Map<String, dynamic> json) => Distributor(
        distributorId: json["distributorID"],
        distributorName: json["distributorName"],
    );

    Map<String, dynamic> toJson() => {
        "distributorID": distributorId,
        "distributorName": distributorName,
    };
}

class Route {
    Route({
        this.routeId,
        this.routeTitle,
    });

    String routeId;
    String routeTitle;

    factory Route.fromJson(Map<String, dynamic> json) => Route(
        routeId: json["routeID"],
        routeTitle: json["routeTitle"],
    );

    Map<String, dynamic> toJson() => {
        "routeID": routeId,
        "routeTitle": routeTitle,
    };
}

List/Map to Model class 列表/映射到 Model class

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM