fromJson function
Creates a new instance of type
, parses the json in jsonStr
and puts
the data into the new instance.
example:
// Simple type conversion
Person person = fromJson('{"id": 1, "name": "John Doe"}', Person);
// List conversion
List<Person> persons = fromJson('[{"id": 1, "name": "John Doe"}]', [() => List<Person>(), Person]);
// Map conversion
Map<String, Person> personsMap = fromJson('{"person1": {"id": 1, "name": "John Doe"}}',
[() => Map<String, Person>(), [String, Person]]);
// Generics conversion
Page<Person> page = fromJson('{
"number": 1,
"size": 3,
"total": 100,
"items": [
{"id": 1, "name": "person1"},
{"id": 2, "name": "person2"},
{"id": 3, "name": "person3"}
]
}', [() => Page<Person>(), {'items': [() => List<Person>(), Person]}]);
Throws NoConstructorError if type
or Classes used inside type
do not
have a constructor without or only optional arguments.
Throws IncorrectTypeTransform if json data types doesn't match.
Throws FormatException if the jsonStr
is not valid JSON text.
Implementation
dynamic fromJson(String jsonStr, /*Type | Function | List<Type | Function | List<Type | Function | ...>>*/ type) {
var filler = json.decode(jsonStr);
return _convertValue(type, filler);
}