There are many ways you can convert a Json object to Dart classes. This tool uses one of these ways which uses a mapping function to map dictionary key values to type safe Dart properties and classes. Here are the steps to convert Json to Dart classes:
Let's take the below JSON string as example and work with it during the steps:
{
"Test": {
"id":4,
"userid":"user_id_value",
"users":[
{
"id":"2",
"name":"Test"
},
{
"id":"6",
"name":"Test Child 1"
}
]
}
}
We can see that we need to create two classes : "Test" and "User" since "users" property is an array of object with two properties "id" and "name".
We can write our Dart classes along with their properties as such:
class Test {
int? id;
String? userid;
List? users;
}
class User {
String? id;
String? name;
}
In Dart, we can simply access properties in a json string by calling the jsonDecode method on the string like so:
const jsonString = '{"myprop": "foo", "mybar": 1}';
// Decoding the json string to a dictionary object
final data = jsonDecode(jsonString);
// Access the dictionary using
print(data['myprop']); // Prints foo
print(data['mybar']); // Prints 1
You will need to import the dart.convert package by adding this line "import 'dart:convert';" at the top of your main function.
Using this logic, we can create a dart function in our previously made classes that will manually map our dictionary to type safe dart properties, which will be explained in the next step.
The next step that needs to be done is mapping each Json node and attributes to Dart classes and properties. We can do so by creating a static method in our Dart classes that's responsible for mapping our dictionary to properties and classes. The Dart code will look like this:
We created "fromJson" methods that will map the supplied JSON dictionary to Dart properties.
Notice that for array objects like "users", we are looping the users' dictionary, creating an instance of a User object, and then adding the user object to the users list.
In order to use your mapper "fromJson" method you do the following in your main function or anywhere in your dart code:
And access your class properties as such:
print(myRootNode.users?[0]?.id);
Notice that we are putting a question mark at each property, this is because we specified in the Test Class
that "List
You can always use the online tool to generate mapping functions and examples, the tool will output the following classes
Notice that the tool creates method to convert from Json and To Json. Tool also wraps your root classes with a master root class, this is in case you have multiple root nodes, the deserialization will be work regardless on how many root nodes you have.
Nullable checking is also implemented by append question mark ? for all the properties as well.
We can see our dart mapping are generated successfully from the tool: