JSON ❤️ Flutter
Tags: flutter, jsonserializable
Published: 2020-05-02 04:07:22

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
```Javascript
class ManualPost {
  int userId;
  int id;
  String title;
  String body;
}
```

#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));
```
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'];
```

#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](https://javiercbk.github.io/json_to_dart/)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/hkobpd42lfwbiz3t5h56.png)

#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.

```yaml
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
```
We are only two steps ahead to generate fromJson & toJson
1) Annotate the class using @JsonSerializable() & attributes using @JsonKey(name:'key')
```dart
@JsonSerializable()
class AutoGenPost {
  @JsonKey(name: 'userId')
  int userId;
  @JsonKey(name: 'id')
  int postId;
  @JsonKey(name: 'title')
  String title;
  @JsonKey(name: 'body')
  String body;
```
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'*.
```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,
    };
```
Now we can refer this file in our model and we can call from & to Json of the generated methods.

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

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

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/e5vcdsoyq8jqfawkrcm6.gif)

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](https://dev-to-uploads.s3.amazonaws.com/i/muo3vr4766uszk1mi5nn.png)
Check out the official documentation for more info
[Flutter Docs](https://flutter.dev/docs/development/data-and-backend/json)

for full sample 
[Github Repo](https://github.com/Prakash-Selvaraj-Ash/prakash.selvaraj-outlook.com/tree/master/json_samples)

Happy fluttering😇😇