Using Pub Package for JSON Parsing with Code Generation.

Mobile Apps Development A-Z Guide.

Volodymyr Babenko
Pharos Production
4 min readMar 1, 2019

--

Give us a message if you’re interested in Blockchain and FinTech software development or just say Hi at Pharos Production Inc.

Or follow us on Youtube to know more about Software Architecture, Distributed Systems, Blockchain, High-load Systems, Microservices, and Enterprise Design Patterns.

Pharos Production Youtube channel

Flutter is a new cross-platform framework that allows us to write an application at the same time on both Android and iOS.
The most convenient way to communicate with the backend application today is the JSON format.
But today parsing must be done manually. Of course, there is nothing difficult in this and many articles have been written about it.

But the problem with manual parsing is that either it is very easy to make a mistake or it is necessary to edit the model in many places while searching for the structure of the response.

So let’s see how you can generate code automatically. As an example, take the relatively complex json. This will be a list of gyms.

{
"message": "accurate",
"cod": "200",
"count": 2,
"list": [
{
"id": 3154578,
"name": "Best Sport Club",
"coord": {
"lat": 50.422222,
"lon": 30.537644
},
"services": {
"gym": true,
"fitness": true,
"sauna": false,
"massage": true,
"pool": false
},
"dt": 1524248100,
"placement": {
"floor": 1,
"square": 340,
"hall_quantity": 2,
"restroom_square": 40 }
},
{ "id": 3154578,
"name": "Underground",
"coord": {
"lat": 50.455841,
"lon": 30.595785 },
"services": {
"gym": true,
"fitness": flase,
"sauna": false,
"massage": false,
"pool": false
},
"dt": 1524288100,
"placement": {
"floor": -1,
"square": 400,
"hall_quantity": 5,
"restroom_square": 15
}
}
]
}

Step 1.

Let’s create a new project in AndroidStudio and add the following dependencies to the pubspec.yaml:

dependencies: 
json_annotation: ^2.0.0

and for developers dependencies:

dev_dependencies:
flutter_test:
sdk: flutter

build_runner: ^1.2.8
json_serializable: ^2.0.2

Step 2.

Create a response. dart file. If the names of the fields in the field do not correspond to the names of the variables in the class, it is necessary to use the @JsonKey(name: ‘original_name’), use the name of the variable. Here is a description of our response:

import 'package:json_annotation/json_annotation.dart';

@JsonSerializable()
class Response {
final String message;
final String code;
final int count;
@JsonKey(name: 'list')
final List<Gym> gyms;

Response(this.message, this.code, this.count, this.gyms);
}

@JsonSerializable()
class Gym {
final int id;
final String name;
final Coordinates coordinates;
final Services services;
@JsonKey(name: 'dt')
final int date;
final Placement placement;

Gym(this.id, this.name, this.coordinates, this.services, this.date, this.placement);
}

@JsonSerializable()
class Coordinates {
final double lat;
final double long;

Coordinates(this.lat, this.long);
}

@JsonSerializable()
class Services {
final bool gym;
final bool fitness;
final bool sauna;
final bool massage;
final bool poll;

Services(this.gym, this.fitness, this.sauna, this.massage, this.poll);
}

@JsonSerializable()
class Placement {
final int floor;
final int square;
@JsonKey(name: 'hall_quantity')
final int hallQuantity;
@JsonKey(name: 'restroom_square')
final int restroomQuantity;

Placement(this.floor, this.square, this.hallQuantity, this.restroomQuantity);
}

Step 3.

In order to generate the necessary code, you need to use the build_runner code generator. Most likely, with a typical installation, the Flutter SDK pub package was not installed and code generation will be impossible. Installation instructions are located at the following link.

In the header file of the response.dart add a link to the file that does not yet exist:

part 'response.g.dart';

Step 4.

Then in the terminal (for convenience, I prefer to use the terminal through the window of the AndroidStudio) execute the following command:

flutter packages pub run build_runner build

This command must be run from the command line, in which pubspec.yaml is situated.

Code generation report.

After that, as you can see, in the folder in which our response.dart file was located, a new response.d.dart file was generated;

Step 5.

But the generated file so far contains errors, namely — there are no “fromJson” constructors for nested classes. Therefore it is necessary to add them manually:

Response(this.message, this.code, this.count, this.gyms);

factory Response.fromJson(Map<String, dynamic> json) => _$ResponseFromJson(json);
------------------------------------------------------------------
Gym(this.id, this.name, this.coordinates, this.services, this.date, this.placement);

factory Gym.fromJson(Map<String, dynamic> json) => _$GymFromJson(json);
------------------------------------------------------------------
Coordinates(this.lat, this.long);

factory Coordinates.fromJson(Map<String, dynamic> json) => _$CoordinatesFromJson(json);
------------------------------------------------------------------
Services(this.gym, this.fitness, this.sauna, this.massage, this.poll);

factory Services.fromJson(Map<String, dynamic> json) => _$ServicesFromJson(json);
}
------------------------------------------------------------------
Placement(this.floor, this.square, this.hallQuantity, this.restroomQuantity);

factory Placement.fromJson(Map<String, dynamic> json) => _$PlacementFromJson(json);

Now, with any changes in the structure of json, it is possible to easily regenerate all constructs.

An example of the project can be found at the link below:

--

--