Convert JSON String or Array into List or Object in Dart/Flutter
In this dart / flutter lesson, we’re going look at how to convert/parse JSON text into Object, Nested Object, how to parse JSON array, array of JSON items into List. Finally, complicated JSON may be parsed into Nested Objects (that also contains array as a field).
Introduction
The jsonDecode top-level method in the dart:convert package can parse a string and return a JSON object (dynamic).
We have 3 stages to convert/parse JSON into Dart Object, Array:
- Obtain JSON object from string using jsonDecode() function
- Create a class with fields that correspond to the JSON key/value pairs and assign the values of each JSON object to the fields of the class instance function fromJson() which will be a factory method
- We’ll implement the parser differently for each type of Object, Nested Object, Basic Array, Array of Objects, and Nested Object containing Array.
Let’s move on to the following portions.
Dart/Flutter Parse JSON String Into Object
Assume we have a JSON structure that looks like this
{
"name": "bezkoder",
"age": 30
}
We’ll make a User
Dart class with two fields: name
and age
.
class User {
String name;
int age;
User(this.name, this.age);
factory User.fromJson(dynamic json) {
return User(json['name'] as String, json['age'] as int);
}
@override
String toString() {
return '{ ${this.name}, ${this.age} }';
}
}
In the code above, you can see the factory User.fromJson() function. A dynamic object is parsed into a User object. So, what’s the best way to retrieve a dynamic object from a JSON string?
The built-in jsonDecode() method of the dart:convert library is used.
import 'dart:convert';
main() {
String objText = '{"name": "bezkoder", "age": 30}';
User user = User.fromJson(jsonDecode(objText));
print(user);
This is what the end outcome will look like.
{ bezkoder, 30 }
Dart/Flutter parse JSON string into Nested Object
As a nested object, like this, with the JSON string.
{
"title": "Dart Tutorial",
"description": "Way to parse Json",
"author": {
"name": "bezkoder",
"age": 30
}
}
There are two types of classes to consider:
-
User
For Author -
Tutorial
for User, Description, and Title
As a result, we may create a new Tutorial
in the same manner.
class User {
String name;
int age;
...
}
class Tutorial {
String title;
String description;
User author;
Tutorial(this.title, this.description, this.author);
factory Tutorial.fromJson(dynamic json) {
return Tutorial(json['title'] as String, json['description'] as String, User.fromJson(json['author']));
}
@override
String toString() {
return '{ ${this.title}, ${this.description}, ${this.author} }';
}
}
The code for the main()
method now looks like this.
import 'dart:convert';
main() {
String nestedObjText =
'{"title": "Dart Tutorial", "description": "Way to parse Json", "author": {"name": "bezkoder", "age": 30}}';
Tutorial tutorial = Tutorial.fromJson(jsonDecode(nestedObjText));
print(tutorial);
Check out the outcome, and you’ll notice our nested object:
{ Dart Tutorial, Way to parse Json, { bezkoder, 30 } }
Dart/Flutter parse JSON array into List
With a basic array such as this
{
"tags": [
"dart",
"flutter",
"json"
]
}
Without having to create a class, we can quickly scan JSON into a Dart array.
import 'dart:convert';
main() {
String arrayText = '{"tags": ["dart", "flutter", "json"]}';
var tagsJson = jsonDecode(arrayText)['tags'];
List<String> tags = tagsJson != null ? List.from(tagsJson) : null;
print(tags);
}
The outcome of printing the Dart Array can now be seen.
[dart, flutter, json]
Dart/Flutter parse array of JSON objects into List
What about a JSON array that’s a little more complicated? Every item in the array, for example, is a JSON object.
{
"tags": [
{
"name": "dart",
"quantity": 12
},
{
"name": "flutter",
"quantity": 25
},
{
"name": "json",
"quantity": 8
}
]
}
A class to represent the Tag item will be required. As a result, we construct a Tag class with two fields, as seen below.
class Tag {
String name;
int quantity;
Tag(this.name, this.quantity);
factory Tag.fromJson(dynamic json) {
return Tag(json['name'] as String, json['quantity'] as int);
}
@override
String toString() {
return '{ ${this.name}, ${this.quantity} }';
}
}
A dynamic object will be parsed into a Tag object using the factory function Tag.fromJson(dynamic json). We’ll need it in the mapping phase of the main() method.
import 'dart:convert';
main() {
String arrayObjsText =
'{"tags": [{"name": "dart", "quantity": 12}, {"name": "flutter", "quantity": 25}, {"name": "json", "quantity": 8}]}';
var tagObjsJson = jsonDecode(arrayObjsText)['tags'] as List;
List<Tag> tagObjs = tagObjsJson.map((tagJson) => Tag.fromJson(tagJson)).toList();
print(tagObjs);
}
Let me explain the code in more detail. It’s straightforward.
- jsonDecode() turns the JSON object ‘tags’ into a dynamic object. After that, we use brackets [‘tags’] to retrieve a JSON array from it.
- Because List produces a List<dynamic>, we’ll use map() to convert each dynamic item in the List to a Tag object.
- Finally, the Iterable result above is converted into a List<Tag> object using
.toList()
.
Now, if we execute the code, we’ll get something like this
[{ dart, 12 }, { flutter, 25 }, { json, 8 }]
Dart/Flutter parse complex JSON into Nested Object
This is the final segment of the tutorial.
We’ll parse a JSON file with several fields and an array of objects field. It appears as follows
{
"title": "Dart Tutorial",
"description": "Way to parse Json",
"author": {
"name": "bezkoder",
"age": 30
},
"tags": [
{
"name": "dart",
"quantity": 12
},
{
"name": "flutter",
"quantity": 25
}
]
}
The Tutorial class is changed to include a new ListTag> tags field.
class Tutorial {
String title;
String description;
User author;
List<Tag> tags;
Tutorial(this.title, this.description, this.author, [this.tags]);
factory Tutorial.fromJson(dynamic json) {
if (json['tags'] != null) {
var tagObjsJson = json['tags'] as List;
List<Tag> _tags = tagObjsJson.map((tagJson) => Tag.fromJson(tagJson)).toList();
return Tutorial(
json['title'] as String,
json['description'] as String,
User.fromJson(json['author']),
_tags
);
} else {
return Tutorial(
json['title'] as String,
json['description'] as String,
User.fromJson(json['author'])
);
}
}
@override
String toString() {
return '{ ${this.title}, ${this.description}, ${this.author}, ${this.tags} }';
}
}
- We use square brackets [this.tags] in the constructor procedure to indicate that this tags array is an option field.
- We use map() and toList() to get ListTag>, similar to how we parse an array of JSON objects into a Dart List.
List<Tag> _tags = tagObjsJson.map((tagJson) => Tag.fromJson(tagJson)).toList();
The main() function now look like this
import 'dart:convert';
main() {
String complexText =
'{"title": "Dart Tutorial", "description": "Way to parse Json", "author": {"name": "bezkoder", "age": 30}, "tags": [{"name": "dart", "quantity": 12}, {"name": "flutter", "quantity": 25}]}';
Tutorial complexTutorial = Tutorial.fromJson(jsonDecode(complexText));
print(complexTutorial);
}
After running the code above, you can see the output with the title, description, author, and tags array.
{ Dart Tutorial, Way to parse Json, { bezkoder, 30 }, [{ dart, 12 }, { flutter, 25 }] }
Conclusion
In this article, we learned how to convert or parse several types of JSON strings into Dart/Flutter Objects and Arrays. The dart:convert
library’s built-in jsonDecode()
method is one of the most significant parts that makes our parsing process straightforward. You can also see how we define the Dart class and use the factory function to transform a dynamic object into a class instance. As always, If you have found this article useful do not forget to share it and leave a comment if you have any questions.
Happy Coding…!
Leave a Reply