JSON ❤️ Flutter

prakashselvaraj

Prakash S

Posted on May 2, 2020

JSON ❤️ Flutter

Now a days in the REST world, JSON is very much important and it transfers between client and server.

JSON (JavaScript Object Notation) is a lightweight data-interchange format

Ok, How do we serialize and deserialize JSON in flutter ??? 🤔🤔

As from my knowledge we can do it three ways 😇
1) Manual
2) Json2Dart using websites
3) Auto Generation

Consider the following model class

class ManualPost {
  int userId;
  int id;
  String title;
  String body;
}
Enter fullscreen mode Exit fullscreen mode

Manual

Convert class to JSON

methods toJson & jsonEncode would help us here.

Map<String, dynamic> toJson() =>
      {'userId': userId, 'id': id, 'title': title, 'body': body};
var post = ManualPost();
post.id = 1;
post.userId = 1;
post.title = "Title";
post.body = "Body";
print(jsonEncode(post));
Enter fullscreen mode Exit fullscreen mode

The above will print like this
{"userId":1,"id":1,"title":"Title","body":"Body"}

Now will see the reverse

JsonString to Class

jsonDecode will help us to get the Map from the json string

With the Map result we can create the instance of our model in two steps
1) Create a constructor with properties
2) Create instance using static funtion fromJson

ManualPost({this.userId, this.id, this.title, this.body});

ManualPost.fromJson(Map<String, dynamic> json)
      : id = json['id'],
        userId = json['userId'],
        title = json['title'],
        body = json['body'];
Enter fullscreen mode Exit fullscreen mode

Json2Dart using websites

There are lot's of website which does the above manual stuff's
one of the website which i used is JsonToDart
Alt Text

AutoGeneration

Thanks to the packages json_serializable, build_runner & json_annotation
These will help us to generate the fromJson & toJson for the model classes.

Let us see in action.!!!!

Add the json_annotation as dependency in pubspec yaml file
Similarly add json_serializable & build_runner as dev dependency in pubspec yaml file.

dependencies:
  flutter:
    sdk: flutter
  json_annotation: ^3.0.1
  cupertino_icons: ^0.1.2

dev_dependencies:
  flutter_test:
    sdk: flutter
  build_runner: ^1.9.0
  json_serializable: ^3.3.0
Enter fullscreen mode Exit fullscreen mode

We are only two steps ahead to generate fromJson & toJson
1) Annotate the class using @JsonSerializable() & attributes using @JsonKey(name:'key')

@JsonSerializable()
class AutoGenPost {
  @JsonKey(name: 'userId')
  int userId;
  @JsonKey(name: 'id')
  int postId;
  @JsonKey(name: 'title')
  String title;
  @JsonKey(name: 'body')
  String body;
Enter fullscreen mode Exit fullscreen mode

2) Run the command flutter pub run build_runner build in your favorite terminal

This will do the magic to create a file like 'filename.g.dart'.

part of 'auto_gen_post.dart';

AutoGenPost _$AutoGenPostFromJson(Map<String, dynamic> json) {
  return AutoGenPost()
    ..userId = json['userId'] as int
    ..postId = json['id'] as int
    ..title = json['title'] as String
    ..body = json['body'] as String;
}

Map<String, dynamic> _$AutoGenPostToJson(AutoGenPost instance) =>
    <String, dynamic>{
      'userId': instance.userId,
      'id': instance.postId,
      'title': instance.title,
      'body': instance.body,
    };
Enter fullscreen mode Exit fullscreen mode

Now we can refer this file in our model and we can call from & to Json of the generated methods.

part 'filename.g.dart';
factory Class.fromJson(Map<String, dynamic> json) => _$ClassFromJson(json);
Map<String, dynamic> toJson() => _$ClassToJson(this);
Enter fullscreen mode Exit fullscreen mode

That's it... we now able to do the serialization and deserialization in flutter 🥰🥰

Alt Text

Some of us might come from C# or Java world, where we have used runtime serialization and de-serialization using generics and reflection. Whereas in flutter we don't have such functionality as of today, due to some limitations. 😫😫
Alt Text
Check out the official documentation for more info
Flutter Docs

for full sample
Github Repo

Happy fluttering😇😇

💖 💪 🙅 🚩
prakashselvaraj
Prakash S

Posted on May 2, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

JSON ❤️ Flutter
flutter JSON ❤️ Flutter

May 2, 2020