Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

flutter - Parsing JSON Object with unique key in Dart

I'm having a hard time figuring out how to parse a JSON response that has unique keys into nested object.

I've done some research and came across this article (https://medium.com/flutter-community/parsing-complex-json-in-flutter-747c46655f51) but it doesn't give an example of a JSON object with unique/random keys.

See below for the json response I get from the backend. The student usernames are unique (i.e. john354, kim553, etc) and a new student could get added at any time. Could someone give me an example of what my model should look like for this type of structure and how to display the data with listview.builder? Thank you so much!

{
    "school": {
        "students": {
            "john354": {
                "fullName": "John Kindle",  
                "permissions": {
                    "permission1": "here",
                    "permission2": "here"
                }
            },
            "kim553": {
                "fullName": "Kim Johnson"
                "permissions": {
                    "permission1": "here",
                    "permission2": "here"
                }
            },
            "dory643": {
                "fullName": "Dory Thomas"
                "permissions": {
                    "permission1": "here",
                    "permission2": "here"
                }
            }
        },
        "footer": "Text goes here"
    },
    "status": {
        "state": "open"
    }
}

Attempt Data Model

class School {
  School school;
  Status status;

  School({this.school, this.status});

  School.fromJson(Map<String, dynamic> json) {
    school =
        json['school'] != null ? new School.fromJson(json['school']) : null;
    status =
        json['status'] != null ? new Status.fromJson(json['status']) : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.school != null) {
      data['school'] = this.school.toJson();
    }
    if (this.status != null) {
      data['status'] = this.status.toJson();
    }
    return data;
  }
}

class School {
  Students students;
  String footer;

  School({this.students, this.footer});

  School.fromJson(Map<String, dynamic> json) {
    students = json['students'] != null
        ? new Students.fromJson(json['students'])
        : null;
    footer = json['footer'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.students != null) {
      data['students'] = this.students.toJson();
    }
    data['footer'] = this.footer;
    return data;
  }
}

class Students {
  final String username;
  final Info info;
  
  Options({this.username,this.info});
    
factory Students.fromJson(String name, Map<String, dynamic> json){
    return Students(
      username: username,
      info: Info(
        fullName: json['info']['fullName']
        )
    );
} 
}

class Info {
  String fullName;
  Permissions permissions;

  Info({this.fullName, this.permissions});

  Info.fromJson(Map<String, dynamic> json) {
    fullName = json['fullName'];
    permissions = json['permissions'] != null
        ? new Permissions.fromJson(json['permissions'])
        : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['fullName'] = this.fullName;
    if (this.permissions != null) {
      data['permissions'] = this.permissions.toJson();
    }
    return data;
  }
}

class Permissions {
  String permission1;
  String permission2;

  Permissions({this.permission1, this.permission2});

  Permissions.fromJson(Map<String, dynamic> json) {
    permission1 = json['permission1'];
    permission2 = json['permission2'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['permission1'] = this.permission1;
    data['permission2'] = this.permission2;
    return data;
  }
}

class Status {
  String state;

  Status({this.state});

  Status.fromJson(Map<String, dynamic> json) {
    state = json['state'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['state'] = this.state;
    return data;
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To simplify JSON pursing you can use app.quicktype.io to convert JSON to DART.

try the Following Data Model,

import 'dart:convert';

School schoolFromJson(String str) => School.fromJson(json.decode(str));

String schoolToJson(School data) => json.encode(data.toJson());

class School {
    School({
        this.school,
        this.status,
    });

    final SchoolClass school;
    final Status status;

    factory School.fromJson(Map<String, dynamic> json) => School(
        school: SchoolClass.fromJson(json["school"]),
        status: Status.fromJson(json["status"]),
    );

    Map<String, dynamic> toJson() => {
        "school": school.toJson(),
        "status": status.toJson(),
    };
}

class SchoolClass {
    SchoolClass({
        this.students,
        this.footer,
    });

    final Map<String, Student> students;
    final String footer;

    factory SchoolClass.fromJson(Map<String, dynamic> json) => SchoolClass(
        students: Map.from(json["students"]).map((k, v) => MapEntry<String, Student>(k, Student.fromJson(v))),
        footer: json["footer"],
    );

    Map<String, dynamic> toJson() => {
        "students": Map.from(students).map((k, v) => MapEntry<String, dynamic>(k, v.toJson())),
        "footer": footer,
    };
}

class Student {
    Student({
        this.fullName,
        this.permissions,
    });

    final String fullName;
    final Permissions permissions;

    factory Student.fromJson(Map<String, dynamic> json) => Student(
        fullName: json["fullName"],
        permissions: Permissions.fromJson(json["permissions"]),
    );

    Map<String, dynamic> toJson() => {
        "fullName": fullName,
        "permissions": permissions.toJson(),
    };
}

class Permissions {
    Permissions({
        this.permission1,
        this.permission2,
    });

    final String permission1;
    final String permission2;

    factory Permissions.fromJson(Map<String, dynamic> json) => Permissions(
        permission1: json["permission1"],
        permission2: json["permission2"],
    );

    Map<String, dynamic> toJson() => {
        "permission1": permission1,
        "permission2": permission2,
    };
}

class Status {
    Status({
        this.state,
    });

    final String state;

    factory Status.fromJson(Map<String, dynamic> json) => Status(
        state: json["state"],
    );

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

To parse this JSON data, do final school = schoolFromJson(jsonString);


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...