Search code examples
jsonflutterjson-deserialization

How can i deserialize my json in Flutter/dart


I'm quite new to flutter and right now i'm stucked in desterilize the json string into my class. Appreciate your help on this.

This is my json

[
 {   
    "itemno": "4800888136473",
    "itemname": "AXE DEO AFRICA 150ML",  
  },
  {  
    "itemno": "4800888141125",
    "itemname": "AXE DEO BODYSPRAY DARK TMPTTN 150ML",   
  }
]

And my JSON Class

class ListItemList{
  ListItemList({   
    this.itemno,
    this.itemname,   
  });


  String itemno;
  String itemname;
  

  factory ListItemList.fromJson(Map<String, dynamic> json) =>
      ListItemList(       
        itemno: json["itemno"],
        itemname: json["itemname"],       
      );
}

How i call

  List<ListItemList> result =
              ListItemList.fromJson(jsonDecode(response.body));

Solution

  • Check this link "https://app.quicktype.io/"

    And paste your json code left side and add class model name.

    for eg.

    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.itemno,
            this.itemname,
        });
    
        String itemno;
        String itemname;
    
        factory User.fromJson(Map<String, dynamic> json) => User(
            itemno: json["itemno"] == null ? null : json["itemno"],
            itemname: json["itemname"] == null ? null : json["itemname"],
        );
    
        Map<String, dynamic> toJson() => {
            "itemno": itemno == null ? null : itemno,
            "itemname": itemname == null ? null : itemname,
        };
    }
    

    //Add below code in service

    static Future<List<User>> getUsers() async {
     List<User> users = usersFromJson(response.body));
     return users;
    }
    

    // call service in specific page

    List _users;

    @override
      void initState() {
        super.initState();
        ApiService.getUsers().then((value) {
              setState(() {
                _users = value;
              });
            })
    }