Convert List Object to JSON java
In this Dart/Flutter JSON encode tutorial, I will show you ways to convert Object, Nested Object, List, List of JSON objects into JSON string. Finally, you can convert a complex Nested Object (that contains some fields and a List of objects field) into JSON string. Show Related Posts: Contents
Overviewdart:convert library provides a built-in top-level function called jsonEncode that can convert many types of Object to JSON string. We have 3 steps to convert an Object/List to JSON string:
For every type of Object, Nested Object, simple List, List of Objects, or Nested Object containing List, we will implement toJson() method with some little difference. Dart/Flutter convert simple Object to JSON stringAssume that we have a User class with fields: name & age. If you call jsonEncode() function without creating toJson() method. You will get an error: Unhandled exception:
Converting object to an encodable object failed: Instance of 'User'
...
Lets create toJson() method like the following code: class User { String name; int age; User(this.name, this.age); Map toJson() => { 'name': name, 'age': age, }; }Now we can use dart:convert librarys built-in jsonEncode() function to convert the User object to JSON string: import 'dart:convert'; main() { User user = User('bezkoder', 21); String jsonUser = jsonEncode(user); print(jsonUser); }The result will show a string like this. {"name":"bezkoder","age":21}Dart/Flutter convert Nested Object to JSON stringIf we have a Tutorial class and author is a field that has User class type. Remember to check if author property is null or not. Check the result, you can see our JSON string: {"title":"Dart Tut#1","description":"Tut#1 Description","author":{"name":"bezkoder","age":21}}Dart/Flutter convert List to JSON stringWe can easily do JSON encode a List without the need of creating any class. The result shows a JSON string array: ["tagA","tagB","tagC"]Dart/Flutter convert List of objects to JSON stringHow about more complicated List? For example, every item in the List is a Tag object. Now everything becomes simple with jsonEncode() function. import 'dart:convert'; main() { ListJSON string looks like an array: [{"name":"tagA","quantity":3},{"name":"tagB","quantity":6},{"name":"tagC","quantity":8}]Dart/Flutter convert complex Nested Object to JSON stringYeah! Youre in the last section of this tutorial. For example, Tutorial class has title, description, author (User class), tags (List Were gonna define the toJson() method like this: class Tutorial { ... Map toJson() { Map author = this.author != null ? this.author.toJson() : null; List |