简体   繁体   中英

Custom deserialization dart objects

what classes I have are:

class Student {
  String name;
  String family;
}
class Info {
  int age;
  String phone;
}

but the server will give me a json like:

{
  "name": "mohammad",
  "family": "nasr",
  "age": 23,
  "phone": "+9345687544",
}

what I want is a class like :

@JsonSerializable()
class JsonResponse {
  Student student;
  Info info;
}

but the problem is that I will give jsonDecoding error because my JsonResponse class doesn't match the server response.

but I want my JsonResponse to be on that form,

If you want your JsonResponse class to be in the form of

@JsonSerializable(explicitToJson: true)
class JsonResponse {
  Student student;
  Info info;
}

and serialize the class, your response will be in the form of { student: {name: mohammad, family: nasr}, info: {age: 23, phone: +9345687544} }, , so you should change the JsonResponse class or use this

JsonResponse jsonResponse = JsonResponse.fromJson(
  Student.fromJson(jsonData), Info.fromJson(jsonData),
);

Just create a deserialization method fromJson as shown below:

class Info {
  int age;
  String phone;

  Info({this.age, this.phone});

  factory Info.fromJson(Map<String, dynamic> json) {
    if(json == null) return null;
    
    return Info(
      age: json['age'],
      phone: json['phone'],
    );
  }
}

class Student {
  String name;
  String family;

  Student({this.name, this.family});

  factory Student.fromJson(Map<String, dynamic> json) {
    if(json == null) return null;
    
    return Student(
      name: json['name'],
      family: json['family'],
    );
  }
}

class JsonResponse {
  Student student;
  Info info;

  JsonResponse({this.student, this.info});

  factory JsonResponse.fromJson(Map<String, dynamic> json) {
    if(json == null) return null;
    
    Student student = Student.fromJson(json);
    Info info = Info.fromJson(json);

    return JsonResponse(student: student, info: info);
  }
}

The fromJson will take in json response from the server & convert it into your corresponding model object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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