Start Coding

Topics

JSON Handling in Dart

JSON (JavaScript Object Notation) is a lightweight data interchange format. Dart provides robust support for working with JSON data, making it easy to parse, manipulate, and generate JSON structures.

Parsing JSON

To parse JSON in Dart, use the jsonDecode() function from the dart:convert library. This function converts a JSON string into a Dart object.


import 'dart:convert';

void main() {
  String jsonString = '{"name": "John", "age": 30}';
  Map<String, dynamic> person = jsonDecode(jsonString);
  print(person['name']); // Output: John
}
    

Encoding Dart Objects to JSON

To convert Dart objects into JSON strings, use the jsonEncode() function. This is useful when sending data to APIs or storing structured data.


import 'dart:convert';

void main() {
  Map<String, dynamic> person = {
    'name': 'Alice',
    'age': 25,
    'hobbies': ['reading', 'swimming']
  };
  String jsonString = jsonEncode(person);
  print(jsonString);
  // Output: {"name":"Alice","age":25,"hobbies":["reading","swimming"]}
}
    

Working with Complex JSON Structures

For more complex JSON structures, consider creating custom classes to represent your data. This approach provides type safety and better code organization.


class Person {
  final String name;
  final int age;

  Person(this.name, this.age);

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

  Map<String, dynamic> toJson() => {
    'name': name,
    'age': age,
  };
}

void main() {
  String jsonString = '{"name": "Emma", "age": 28}';
  Person person = Person.fromJson(jsonDecode(jsonString));
  print(person.name); // Output: Emma

  String encodedPerson = jsonEncode(person);
  print(encodedPerson); // Output: {"name":"Emma","age":28}
}
    

Best Practices

  • Always handle potential exceptions when parsing JSON to avoid runtime errors.
  • Use strong typing with custom classes for complex JSON structures.
  • Consider using packages like json_serializable for automatic JSON serialization in large projects.
  • Validate JSON data before processing to ensure data integrity.

Related Concepts

To further enhance your Dart skills, explore these related topics:

Mastering JSON handling in Dart is crucial for developing robust applications, especially when working with APIs or storing structured data. With Dart's built-in functions and libraries, you can efficiently parse, manipulate, and generate JSON data in your projects.