Dart: Convert/Parse JSON String, Array into List/Object

Convert JSON String or Array into List or Object in Dart/Flutter

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 }
Code language: JSON / JSON with Comments (json)

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} }'; } }
Code language: JavaScript (javascript)

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);
Code language: JavaScript (javascript)

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 } }
Code language: JSON / JSON with Comments (json)

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} }'; } }
Code language: JavaScript (javascript)

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);
Code language: JavaScript (javascript)

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" ] }
Code language: JSON / JSON with Comments (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); }
Code language: JavaScript (javascript)

The outcome of printing the Dart Array can now be seen.

[dart, flutter, json]
Code language: JSON / JSON with Comments (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 } ] }
Code language: JSON / JSON with Comments (json)

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} }'; } }
Code language: JavaScript (javascript)

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); }
Code language: JavaScript (javascript)

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 }]
Code language: CSS (css)

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 } ] }
Code language: JSON / JSON with Comments (json)

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} }'; } }
Code language: JavaScript (javascript)
  • 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();
Code language: JavaScript (javascript)

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); }
Code language: JavaScript (javascript)

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 🙂

%d bloggers like this: