How to decode JSON in Flutter?

CodeWithFlutter
2 Min Read

In Flutter, you can use the dart:convert library to parse JSON data. Here’s an example of how you can parse a JSON string into a Dart object:

import 'dart:convert';

String jsonString = '{"name": "John Doe", "email": "[email protected]"}';

Map<String, dynamic> userData = jsonDecode(jsonString);

print(userData['name']); // Output: John Doe
print(userData['email']); // Output: [email protected]

You can also parse JSON data into a custom Dart object. To do this, you’ll need to create a class that represents the data, and then use jsonDecode to parse the JSON into an instance of that class:

class User {
  final String name;
  final String email;

  User({this.name, this.email});

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      name: json['name'],
      email: json['email'],
    );
  }
}

String jsonString = '{"name": "John Doe", "email": "[email protected]"}';

User user = User.fromJson(jsonDecode(jsonString));

print(user.name); // Output: John Doe
print(user.email); // Output: [email protected]

This approach is especially useful when working with complex JSON structures. By using a custom class, you can define the structure of the data and provide getters and setters for the properties, making it easier to access and manipulate the data in your app.

Share this Article
Leave a comment