Flutter dart decode and parse json to object

1. Here is a json string saved in the variable jsonData. It represents a pokemon. In this case, a Bulbasaur.

final jsonData = '{ "id": 1, "name": "Bulbasaur" }';

2. Here is a data model class for a pokemon. The constructor takes 2 parameters because id and name are the only properties. The factory function fromJson takes in a Map and converts it to an object. The toJson function converts the object to a Map.

class Pokemon {
  Pokemon({required this.id, required this.name});
  final int id;
  final String name;

  factory Pokemon.fromJson(Map data) {
    final id = data['id'] as int;
    final name = data['name'] as String;
    return Pokemon(id: id, name: name);
  }

  Map toJson() {
    return {
      'id': id,
      'name': name,
    };
  }

  @override
  String toString() => toJson().toString();

}

3. jsonString is the raw json string, decodedJson is the decoded json string in a map of String to dynamic, parsedJson is the final object.

import 'dart:convert';

final String jsonString = '{ "id": 1, "name": "Bulbasaur" }';
final Map decodedJson = json.decode(jsonString);
final Pokemon parsedJson = Pokemon.fromJson(decodedJson);

Search within Codexpedia

Custom Search

Search the entire web

Custom Search