Flutter - How do I parse JSON from the API


Parse JSON string in flutter

Answers

  • September 5, 2021

    Parsing JSON is a common functionality in every mobile application

    We can parse JSON in two ways

    1. write all the JSON parsing code for each keys
    2. Work with auto generated code

     

    Write all keys for json to parse by

    • encoding and decoding JSON
    • defining type-safe model classes
    • parsing JSON to Dart code using a factory constructor
    • dealing with nullable/optional values
    • data validation
    • serializing back to JSON
    • parsing complex/nested JSON data

     

    Convert JSON Pojo classes

    import 'dart:convert';
    
    List<Albums> albumsFromJson(String str) => List<Albums>.from(json.decode(str).map((x) => Albums.fromJson(x)));
    
    String albumsToJson(List<Albums> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
    
    class Albums {
      Albums({
        required this.userId,
        required this.id,
        required this.title,
      });
    
      late int userId;
      late int id;
      late  String title;
    
      factory Albums.fromJson(Map<String, dynamic> json) => Albums(
        userId: json["userId"],
        id: json["id"],
        title: json["title"],
      );
    
      Map<String, dynamic> toJson() => {
        "userId": userId,
        "id": id,
        "title": title,
      };
    }

     

    Here is the example to Fetch data from network and parse JSON data

     

     

    Comment

Have More Question?

Subscribe For Daily Updates

Flutter Questions
Android Questions