json to object flutter dart code example
Example 1: json to dart
class Autogenerated {
int postId;
int id;
String name;
String email;
String body;
Autogenerated({this.postId, this.id, this.name, this.email, this.body});
Autogenerated.fromJson(Map json) {
postId = json['postId'];
id = json['id'];
name = json['name'];
email = json['email'];
body = json['body'];
}
Map toJson() {
final Map data = new Map();
data['postId'] = this.postId;
data['id'] = this.id;
data['name'] = this.name;
data['email'] = this.email;
data['body'] = this.body;
return data;
}
}
Example 2: json to class dart
The Data:
For this example, let's assume that my data looks something like this:
{
"type": "articles",
"id": "1",
"data": [
"val",
"val2"
],
"author": {
"id": "42",
"name": "bo"
}
}
This data object is rather simple but will help us highlight all the important cases that we care about.
Our Classes:
In this example, we have 2 classes that we are working with: Document.dart
class Document {
final String type;
final int id;
final List data;
final Author author;
Document({this.type, this.id, this.data, this.author});
// add fromJson method here
}
and our Author.dart
class Author{
final int id;
final String name;
Author({this.id, this.name});
// add fromJson method here
}
FromJson Methods:
Let’s first start with our Author class as it has no nested class objects in it.
class Author{
final int id;
final String name;
Author({this.id, this.name});
factory Author.fromJson(Map json) {
return Author(
id: json["id"],
name: json["name"],
);
}
}
As you can see, it’s a rather simple method when you are dealing with just converting simple variables from JSON into your class objects. To ensure we don’t have any issues with the format in which the data is received from our APIs, you can go a step further and cast the JSON values into your object type like so:
json["name"].toString()
This is not necessary, but sometimes useful if the source of the API is not reliable or a professional service. I’ve seen instances in the past where when a double is equal to 0, the JSON object reads it as an int instead of a double which then throws an error. Casting your value into a variable type is a safe way of handling those rare cases.
Next, let’s take a look at our parent class, Document:
class Document {
final String type;
final int id;
final List data;
final Author author;
Document({this.type, this.id, this.data, this.author});
factory Document.fromJson(Map json) {
var dataObj = json['data'];
return Document(
type: json["type"],
id: json["id"],
data: new List.from(dataObj),
author: Author.fromJson(json['author']),
);
}
}