CodeBlanks Logo Icon CodeBlanks

fromJson

Learn to create objects with fromJson.

The fromJson factory

fromJson is a factory method that builds an instance from a JSON Map. It provides type-safe access; safer than dynamic.

Example: factory User.fromJson(Map<String, dynamic> m) => User(m['name'] as String, m['age'] as int);. Each JSON field is cast.

Usage: var u = User.fromJson(jsonDecode(s) as Map<String, dynamic>);. Now u.name works with type safety.

Null-safe fromJson

JSON fields may be missing; therefore fromJson is written null-safe. m['name'] as String? makes it nullable, or a default is given: m['name'] ?? 'guest'.

For numeric fields, (m['age'] as num).toInt() is safe; the int/double distinction in JSON can be ambiguous.

For nested objects, the inner class's fromJson is called: Address.fromJson(m['address'] as Map<String, dynamic>).

Practice Define User.fromJson

Define class User { String name; int age; User(this.name, this.age); factory User.fromJson(Map<String, dynamic> m) => User(m['name'] as String, m['age'] as int); }. Inside main add var u = User.fromJson({'name': 'Ayşe', 'age': 30}); and print(u.name);.

Starter code

main.dart
void main() {
  // define the User class with fromJson (outside main)
  // create an instance via fromJson; print name
}

Sample solution

main.dart
class User {
  String name;
  int age;
  User(this.name, this.age);
  factory User.fromJson(Map<String, dynamic> m) =>
      User(m['name'] as String, m['age'] as int);
}

void main() {
  var u = User.fromJson({'name': 'Ayşe', 'age': 30});
  print(u.name);
}

Expected output

Ayşe

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the fromJson parts

Term Meaning
factory Factory keyword
Map<String, dynamic> Input type
as String Type cast
User(...) Instance creation

2 What does fromJson return?

  • String
  • Map
  • Class instance Correct answer
  • Future

Explanation: fromJson returns a class instance.

3 Type cast

Question
m['name'] ____ String
Answer
m['name'] as String

Explanation: 'as String' casts dynamic to String.

All lessons in Advanced