Home > Back-end >  I want to acces value from json response in flutter
I want to acces value from json response in flutter

Time:10-19

JSON RESPONSE

{
    "cookie": "[email protected]|1697625092|Vp3S5R4HYCnBZvzObZXn3lxELeppURrwzkDNsueAcMT|86e608657c3293607142b8e1f04bcf477e7d7607bae4166424b0b21f517c83e4",
    "cookie_name": "wordpress_logged_in_756f7f794e89ac60ad1c3919face90fa",
    "user": {
        "id": 13,
        "username": "[email protected]",
        "nicename": "user1gmail-com",
        "email": "[email protected]",
        "url": "",
        "registered": "2022-10-18 05:48:42",
        "displayname": "[email protected]",
        "firstname": "",
        "lastname": "",
        "nickname": "[email protected]",
        "description": "",
        "capabilities": {
            "subscriber": true
        },
        "role": [
            "subscriber"
        ],
        "shipping": null,
        "billing": null,
        "avatar": "https://secure.gravatar.com/avatar/59029276955677351421b3ff6bf5ee4c?s=96&d=mm&r=g",
        "is_driver_available": false,
        "dokan_enable_selling": ""
    }
}

I want to access role value in user in my flutter code, i am not sure how can i get role value from my JSON Response.
Here is my Flutter Code

LoginResponseModel.fromJson(Map<String, dynamic> json) {
    token = json['cookie'];
    data = Data.fromJson(json['user']);
  }
  Map<String, dynamic> toJson() {
    Map<String, dynamic> data = Map<String, dynamic>();
    data['user'] = this.data.toJson();
   
    return data;
  }

DATA CLASS

class Data {
  late String token;
  late int id;
  late String email;
  late String nicename;
  late String firstName;
  late String lastName;
  late String displayName;
  Data(
      {required this.token,
      required this.id,
      required this.email,
      required this.firstName,
      required this.lastName,
      required this.displayName,
      required this.nicename});
  Data.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    token = json['cookie'] ?? '';
    email = json['email'] ?? '';
    firstName = json['firstName'] ?? '';
    lastName = json['lastName'] ?? '';
    displayName = json['displayName'] ?? '';
    nicename = json['nicename'] ?? '';
  }
  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = Map<String, dynamic>();
    data['id'] = id;
    data['email'] = email;
    data['firstName'] = firstName;
    data['lastName'] = lastName;
    data['displayName'] = displayName;
    data['nicename'] = nicename;
    return data;
  }

CodePudding user response:

Firstly you can use this particular tool for creating the data classes from Json. https://app.quicktype.io/

Your data class would look like that

import 'dart:convert';

Data dataFromJson(String str) => Data.fromJson(json.decode(str));

String dataToJson(Data data) => json.encode(data.toJson());

class Data {
    Data({
        this.cookie,
        this.cookieName,
        this.user,
    });

    String cookie;
    String cookieName;
    User user;

    factory Data.fromJson(Map<String, dynamic> json) => Data(
        cookie: json["cookie"],
        cookieName: json["cookie_name"],
        user: User.fromJson(json["user"]),
    );

    Map<String, dynamic> toJson() => {
        "cookie": cookie,
        "cookie_name": cookieName,
        "user": user.toJson(),
    };
}

class User {
    User({
        this.id,
        this.username,
        this.nicename,
        this.email,
        this.url,
        this.registered,
        this.displayname,
        this.firstname,
        this.lastname,
        this.nickname,
        this.description,
        this.capabilities,
        this.role,
        this.shipping,
        this.billing,
        this.avatar,
        this.isDriverAvailable,
        this.dokanEnableSelling,
    });

    int id;
    String username;
    String nicename;
    String email;
    String url;
    DateTime registered;
    String displayname;
    String firstname;
    String lastname;
    String nickname;
    String description;
    Capabilities capabilities;
    List<String> role;
    dynamic shipping;
    dynamic billing;
    String avatar;
    bool isDriverAvailable;
    String dokanEnableSelling;

    factory User.fromJson(Map<String, dynamic> json) => User(
        id: json["id"],
        username: json["username"],
        nicename: json["nicename"],
        email: json["email"],
        url: json["url"],
        registered: DateTime.parse(json["registered"]),
        displayname: json["displayname"],
        firstname: json["firstname"],
        lastname: json["lastname"],
        nickname: json["nickname"],
        description: json["description"],
        capabilities: Capabilities.fromJson(json["capabilities"]),
        role: List<String>.from(json["role"].map((x) => x)),
        shipping: json["shipping"],
        billing: json["billing"],
        avatar: json["avatar"],
        isDriverAvailable: json["is_driver_available"],
        dokanEnableSelling: json["dokan_enable_selling"],
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "username": username,
        "nicename": nicename,
        "email": email,
        "url": url,
        "registered": registered.toIso8601String(),
        "displayname": displayname,
        "firstname": firstname,
        "lastname": lastname,
        "nickname": nickname,
        "description": description,
        "capabilities": capabilities.toJson(),
        "role": List<dynamic>.from(role.map((x) => x)),
        "shipping": shipping,
        "billing": billing,
        "avatar": avatar,
        "is_driver_available": isDriverAvailable,
        "dokan_enable_selling": dokanEnableSelling,
    };
}

class Capabilities {
    Capabilities({
        this.subscriber,
    });

    bool subscriber;

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

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

After that you can parse it like that.

// To parse this JSON data, do

final data = dataFromJson(jsonString);
final role = data.user.role[0]; // Inorder to get the role value from json.

CodePudding user response:

Add another variable to your Data class like :

late List<String> role;

then pass value like this in Data.fromJson:

Data.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    token = json['cookie'] ?? '';
    email = json['email'] ?? '';
    firstName = json['firstName'] ?? '';
    lastName = json['lastName'] ?? '';
    displayName = json['displayName'] ?? '';
    nicename = json['nicename'] ?? '';
    role = json['nicename'] ?? [];
  }

and you can access it in user like this:

var loginData = LoginResponseModel(...);

print(" role 1 = ${loginData.data.role[0]}");//role 1 = subscriber
  • Related