如何使用fromJson和toJson时,json对象有另一个对象,如在Flutter

e5njpo68  于 2023-06-30  发布在  Flutter
关注(0)|答案(4)|浏览(155)

当我调用getall endpoint时,它给了我下面的json对象,我将把该值绑定到一个Entity类。但不能分配新值或访问响应值。因为它内部有另一个json对象。我将在下面附加代码。
我想知道创建一个实体的正确顺序,JSON对象有几个对象的JSON对象ID在Flutter

[
    {
        "id": "931992ff-6ec6-43c9-a54c-b1c5601d58e5",
        "sp_id": "062700016",
        "phone_number": "+94716035826",
        "nic": "991040293V",
        "**drivers_license**": {
            "license_id": "12345678",
            "expiry_date": "2023-09-36"
        },
        "user_level": "",
        "gender": "Male",
        "user_sub_type": "app_user",
        "is_fleet_owner": false,
        "fleet_id": "",
        "documents": null,
        "payment_parameters": {
            "account_holder_name": "",
            "bank_name": "",
            "branch_name": "",
            "account_number": "",
            "swift_code": ""
        }
    }
]
  • 我想创建json中加粗的实体,调用“drivers_license”对象 *

我试过像这样的实体类,但是不能正确理解如何实现像json上面的drivers_license的一部分。

class ServiceProviderModel {
  String id = "";
  String phone_number = "";
  String nic = "";
  String license_id = "";
  String expiry_date = "";
  String gender = "";
  String user_sub_type = "";
  String document_type_1 = "";
  String document_type_2 = "";
  String first_name = "";
  String last_name = "";
  String email = "";
  String profile_pic_url = "";
  String emergency_contact = "";
  String status = "active";

  ServiceProviderModel();

  ServiceProviderModel.fromJson(Map json)
      : id = json['id'],
        phone_number = json['phone_number'],
        nic = json['nic'],
        license_id = json['license_id'],
        gender = json['gender'],
        user_sub_type = json['user_sub_type'],
        document_type_1 = json['document_type_1'],
        document_type_2 = json['document_type_2'],
        first_name = json['first_name'],
        last_name = json['last_name'],
        email = json['email'],
        profile_pic_url = json['profile_pic_url'],
        emergency_contact = json['emergency_contact'],
        expiry_date = json['expiry_date'],
        status = json['status'];

  Map toJson() => {
        'id': id,
        'phone_number': phone_number,
        'nic': nic,
        'license_id': license_id,
        'gender': gender,
        'user_sub_type': user_sub_type,
        'document_type_1': document_type_1,
        'document_type_2': document_type_2,
        'first_name': first_name,
        'last_name': last_name,
        'email': email,
        'profile_pic_url': profile_pic_url,
        'emergency_contact': emergency_contact,
        'expiry_date': expiry_date,
        'status': status,
      };
}
ndasle7k

ndasle7k1#

我建议使用像https://app.quicktype.io/这样的工具。输入您的示例JSON可以生成以下示例

import 'dart:convert';

class ServiceProviderModel {
    String id;
    String spId;
    String phoneNumber;
    String nic;
    DriversLicense driversLicense;
    String userLevel;
    String gender;
    String userSubType;
    bool isFleetOwner;
    String fleetId;
    dynamic documents;
    PaymentParameters paymentParameters;

    ServiceProviderModel({
        required this.id,
        required this.spId,
        required this.phoneNumber,
        required this.nic,
        required this.driversLicense,
        required this.userLevel,
        required this.gender,
        required this.userSubType,
        required this.isFleetOwner,
        required this.fleetId,
        this.documents,
        required this.paymentParameters,
    });

    factory ServiceProviderModel.fromJson(String str) => ServiceProviderModel.fromMap(json.decode(str));

    String toJson() => json.encode(toMap());

    factory ServiceProviderModel.fromMap(Map<String, dynamic> json) => ServiceProviderModel(
        id: json["id"],
        spId: json["sp_id"],
        phoneNumber: json["phone_number"],
        nic: json["nic"],
        driversLicense: DriversLicense.fromMap(json["drivers_license"]),
        userLevel: json["user_level"],
        gender: json["gender"],
        userSubType: json["user_sub_type"],
        isFleetOwner: json["is_fleet_owner"],
        fleetId: json["fleet_id"],
        documents: json["documents"],
        paymentParameters: PaymentParameters.fromMap(json["payment_parameters"]),
    );

    Map<String, dynamic> toMap() => {
        "id": id,
        "sp_id": spId,
        "phone_number": phoneNumber,
        "nic": nic,
        "drivers_license": driversLicense.toMap(),
        "user_level": userLevel,
        "gender": gender,
        "user_sub_type": userSubType,
        "is_fleet_owner": isFleetOwner,
        "fleet_id": fleetId,
        "documents": documents,
        "payment_parameters": paymentParameters.toMap(),
    };
}

class DriversLicense {
    String licenseId;
    String expiryDate;

    DriversLicense({
        required this.licenseId,
        required this.expiryDate,
    });

    factory DriversLicense.fromJson(String str) => DriversLicense.fromMap(json.decode(str));

    String toJson() => json.encode(toMap());

    factory DriversLicense.fromMap(Map<String, dynamic> json) => DriversLicense(
        licenseId: json["license_id"],
        expiryDate: json["expiry_date"],
    );

    Map<String, dynamic> toMap() => {
        "license_id": licenseId,
        "expiry_date": expiryDate,
    };
}

class PaymentParameters {
    String accountHolderName;
    String bankName;
    String branchName;
    String accountNumber;
    String swiftCode;

    PaymentParameters({
        required this.accountHolderName,
        required this.bankName,
        required this.branchName,
        required this.accountNumber,
        required this.swiftCode,
    });

    factory PaymentParameters.fromJson(String str) => PaymentParameters.fromMap(json.decode(str));

    String toJson() => json.encode(toMap());

    factory PaymentParameters.fromMap(Map<String, dynamic> json) => PaymentParameters(
        accountHolderName: json["account_holder_name"],
        bankName: json["bank_name"],
        branchName: json["branch_name"],
        accountNumber: json["account_number"],
        swiftCode: json["swift_code"],
    );

    Map<String, dynamic> toMap() => {
        "account_holder_name": accountHolderName,
        "bank_name": bankName,
        "branch_name": branchName,
        "account_number": accountNumber,
        "swift_code": swiftCode,
    };
}

它可能没有像你希望的确切格式,但你可以调整它到你的愿望,并得到一个好主意,如何可能做到这一点

ep6jt1vc

ep6jt1vc2#

通常,你会为你的子实体创建一个新的类,并带有属性,以及自己的from和to json方法。然后在父类的fromJson方法中调用这些方法。

classe DriversLicense {
    final String license_id;
    final String expiry_date;

    factory Post.fromJson(Map<String, dynamic> json) {
    return DriversLicense(
      license_id: json['id'],
      expiry_date: json['expiry_date'] ?? ""
    );
  }
}

伪代码供您插入。

class ServiceProviderModel {
...
DriversLicense drivers_license;
...

ServiceProviderModel.fromJson(Map json)
      : id = json['id'],
      ...
      drivers_license = DriversLicense.fromJson(json['license_id']),
      ...

这里有一个更完整的例子,从我自己的项目。这会将类设置为不可变的,并提供一个copyWith方法来将更改应用到新示例。不包括toJson(),但在结构方面与您目前拥有的基本相同。

import 'package:lon_flutter_poc_app/data/graphql/gen/author.dart';

// THIS IS GENERATED BY CODE. YOU WILL LOOSE MANUAL CHANGES!
class Post {
  final int id;
  final String title;
  final Author author;
  final int votes;

  Post({required this.id, required this.title, required this.author, required this.votes});

  // THIS IS GENERATED BY CODE. YOU WILL LOOSE MANUAL CHANGES!

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      id: json['id'],
      title: json['title'] ?? "",
      author: Author.fromJson(json['author'] ?? {}),
      votes: json['votes'],
    );
  }

  // THIS IS GENERATED BY CODE. YOU WILL LOOSE MANUAL CHANGES!
  Post copyWith({
    int? id,
    String? title,
    Author? author,
    int? votes,
  }) {
    return Post(
      id: id ?? this.id,
      title: title ?? this.title,
      author: author ?? this.author,
      votes: votes ?? this.votes,
    );
  }
}
import 'package:lon_flutter_poc_app/data/graphql/gen/post.dart';

// THIS IS GENERATED BY CODE. YOU WILL LOOSE MANUAL CHANGES!
class Author {
  final int id;
  final String firstName;
  final String lastName;

  Author({required this.id, required this.firstName, required this.lastName});

  // THIS IS GENERATED BY CODE. YOU WILL LOOSE MANUAL CHANGES!

  factory Author.fromJson(Map<String, dynamic> json) {

    return Author(
      id: json['id'],
      firstName: json['firstName'] ?? "",
      lastName: json['lastName'] ?? ""
    );
  }

  // THIS IS GENERATED BY CODE. YOU WILL LOOSE MANUAL CHANGES!
  Author copyWith({
    int? id,
    String? firstName,
    String? lastName,
  }) {
    return Author(
      id: id ?? this.id,
      firstName: firstName ?? this.firstName,
      lastName: lastName ?? this.lastName
    );
  }
}
x6h2sr28

x6h2sr283#

我找到了这个问题的一个很好的答案,我使用下面的代码来解决这个问题。这是非常简单和干净

class ServiceProviderModel {
  String id = "";
  String phone_number = "";
  String nic = "";
  Map drivers_license = new Map();
  String license_id = "";
  String expiry_date = "";
  String gender = "";
  String user_sub_type = "";
  Map documents = new Map();
  String document_type_1 = "";
  String document_type_2 = "";
  String first_name = "";
  String last_name = "";
  String email = "";
  String profile_pic_url = "";
  String emergency_contact = "";
  String status = "active";

  ServiceProviderModel();

  ServiceProviderModel.fromJson(Map json)
      : id = json['id'],
        phone_number = json['phone_number'],
        nic = json['nic'],
        drivers_license = json['drivers_license'],
        gender = json['gender'],
        user_sub_type = json['user_sub_type'],
        documents = json['documents'],
        first_name = json['first_name'],
        last_name = json['last_name'],
        email = json['email'],
        profile_pic_url = json['profile_pic_url'],
        emergency_contact = json['emergency_contact'],
        status = json['status'];

  Map toJson() =>
      {
        'id': id,
        'phone_number': phone_number,
        'nic': nic,
        'drivers_license': drivers_license,
        'gender': gender,
        'user_sub_type': user_sub_type,
        'documents': documents,
        'first_name': first_name,
        'last_name': last_name,
        'email': email,
        'profile_pic_url': profile_pic_url,
        'emergency_contact': emergency_contact,
        'status': status,
      };
}
eeq64g8w

eeq64g8w4#

你可以看到这个例子:

class User {
int id;
String name;

User({
    required this.id,
    required this.name,
});

factory User.fromJson(Map<String, dynamic> json) => User(
    id: json["id"],
    name: json["name"],
);

Map<String, dynamic> toJson() => {
    "id": id,
    "name": name,
};
}

String? User;
var getUserURL = Uri.parse("https://");

Future<void> getUser(String phoneNumber, String password) async {
  String clientHashString = userModel.clientHash!;
  final jsonBody = {'phoneNumber': phoneNumber, 'password': password};

try {
  final response = await http.post(getUserURL, body: jsonBody);
  if (response.statusCode == 200) {
    final userObject = json.decode(response.body);
    User = User.fromJson(userObject);
    print("User Loaded");
  } else {
    customSnackBar("error_text".tr, "something_went_wrong_text".tr, red);
    print(response.body);
  }
} catch (e) {
  throw Exception('Failed to load User');
}

}
如果你有serval JSON Object,那么试试这个,你可以在你模型中尝试这个,但是你必须为你的serval JSON对象创建另一个模型:

coupon: json["coupon"] != null ? CouponTransactionModel.fromJson(json["coupon"]) : null,

在您的案例中:

class DriversLicense {
int id;
String name;

DriversLicense({
    required this.id,
    required this.name,
});

factory DriversLicense.fromJson(Map<String, dynamic> json) => DriversLicense(
    id: json["id"],
    name: json["name"],
);

Map<String, dynamic> toJson() => {
    "id": id,
    "name": name,
};
}

用户模型此函数将被修改如下:

factory User.fromJson(Map<String, dynamic> json) => User(
    id: json["id"],
    name: json["name"],
    drivingLicense: DrivingLicense.fromJson(json["**drivers_license**"])
);

相关问题