Flutter
fromJson
Build a model from JSON with the fromJson factory.
The fromJson factory constructor
By adding a fromJson factory constructor to a model class, you turn a JSON Map into a model object. The factory keyword lets the constructor create and return a new instance. You cast JSON values with as for safe access.
class Kullanici {
final String ad;
final int yas;
Kullanici(this.ad, this.yas);
factory Kullanici.fromJson(Map<String, dynamic> json) {
return Kullanici(
json['ad'] as String,
json['yas'] as int,
);
}
}
Casting values
Casting each value explicitly inside fromJson catches errors early. If a field is missing or has the wrong type, the as cast throws at runtime, so you can easily locate the problem.
final m = {'ad': 'Cem', 'yas': 'otuz'};
// Kullanici.fromJson(m); // Error: 'otuz' is not int
final m2 = {'ad': 'Cem', 'yas': 30};
final k = Kullanici.fromJson(m2);
print(k.yas); // 30
Exercise Add the fromJson constructor
Add a fromJson factory constructor to the Kullanici class. In main, create an instance from the given Map and print its ad field.
Show example solution
class Kullanici {
final String ad;
final int yas;
Kullanici(this.ad, this.yas);
factory Kullanici.fromJson(Map<String, dynamic> json) {
return Kullanici(
json['ad'] as String,
json['yas'] as int,
);
}
}
void main() {
final m = {'ad': 'Ela', 'yas': 22};
final k = Kullanici.fromJson(m);
print(k.ad);
}
Test yourself
-
How is fromJson defined?
- As a void method
- As an async function
- As an overridden method
- As a factory constructor
Show answer
As a factory constructor — fromJson is defined as a factory constructor in the lessons. void returns nothing, async requires a Future return, and override is for overriding an inherited method.
-
Factory constructor keyword
class Kullanici {
final String ad;
final int yas;
Kullanici(this.ad, this.yas);
____ Kullanici.fromJson(Map<String, dynamic> json) {
return Kullanici(json['ad'] as String, json['yas'] as int);
}
}
Show answer
class Kullanici {
final String ad;
final int yas;
Kullanici(this.ad, this.yas);
factory Kullanici.fromJson(Map<String, dynamic> json) {
return Kullanici(json['ad'] as String, json['yas'] as int);
}
}
-
fromJson parts
- factory
- Factory constructor keyword
- Map<String, dynamic>
- Input parameter
- json['ad'] as String
- Value cast
- return Kullanici(...)
- Object return
Next lesson: toJson