Converting JSON value into dart class objects | JSON serialization | Flutter and dart Extensions

Vijay R
vijaycreations
Published in
5 min readFeb 18, 2023

In this article we will discuss about how to convert JSON object into dart model class at a push of a button. No matter how complex the JSON is going to be, we will try to generate dart models easily using one of the extensions readily available in VS code itself which makes the process even more simple.

Refer my video tutorial 👇 for detailed walk through about the implementation process.

🎥 Video Tutorial

🔭 Implementation

The UI is going to be very simple. Let’s have an appbar and an elevated button placed right at the center, which when clicked will try to mimic the process of api call and fetch the data from fake local repository after serializing the JSON values.

class MyHomePage extends StatelessWidget {
const MyHomePage({
required this.title,
Key? key,
}) : super(key: key);

final String title;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(title)),
body: Center(
child: ElevatedButton(
onPressed: () => funCall(),
child: const Text('Get Data'),
),
));
}

funCall() async {
var temp = await HomePageRepo().getData();
}
}

The JSON value what we are about to use is written down in a separate dart file and is as follows.,

var jsonVal = {
"name": "Alice",
"dob": {
"year": 2021,
"month": 1,
"day": 1,
},
"reviews": [
{"score": 4.5, "review": "This is amazing!"},
{"score": 5.0, "review": "Excellent service!"}
],
"address": {
"city": "CityX",
"code": {
"postcode": 123,
"zipcode": 111,
}
}
};

Now consider this 👆 JSON is what we will get as a result of making the API call. So now let try to create a model class for it.

Inside a separate dart file, let’s create a class that holds the primary data members of the JSON object and create a constructor for the same.

class HomePageModel {
final String name;
final Map<String, Object> address;
final Map<String, Object> dob;
final List<Map<String, Object>> reviews;

HomePageModel(
this.name,
this.address,
this.dob,
this.reviews,
);

After doing so, if you are working on VS code, then go to the extensions tab and search for Dart Data Class Generator and install the extension in your VS Code. If you are doing it for the first time make sure your restart your VS Code to make sure the extension works properly.

After installing the extension. Now go the model class which we created above and make use of quick fix and you will now see an option called generate data class. Select it and it will does the rest of creating the copyWith, toMap, fromMap, toJson, fromJson, toString, operator == and hashCode methods.

The generated code is as follows.,

import 'dart:convert';

import 'package:flutter/foundation.dart';

class HomePageModel {
final String name;
final Map<String, Object> address;
final Map<String, Object> dob;
final List<Map<String, Object>> reviews;

HomePageModel(
this.name,
this.address,
this.dob,
this.reviews,
);

HomePageModel copyWith({
String? name,
Map<String, Object>? address,
Map<String, Object>? dob,
List<Map<String, Object>>? reviews,
}) {
return HomePageModel(
name ?? this.name,
address ?? this.address,
dob ?? this.dob,
reviews ?? this.reviews,
);
}

Map<String, dynamic> toMap() {
return <String, dynamic>{
'name': name,
'address': address,
'dob': dob,
'reviews': reviews,
};
}

factory HomePageModel.fromMap(Map<String, dynamic> map) {
return HomePageModel(
map['name'] as String,
Map<String, Object>.from(
(map['address'] as Map<String, Object>),
),
Map<String, Object>.from(
(map['dob'] as Map<String, Object>),
),
List<Map<String, Object>>.from(
(map['reviews'] as List<dynamic>).map<Map<String, Object>>(
(x) => x,
),
),
);
}

String toJson() => json.encode(toMap());

factory HomePageModel.fromJson(String source) =>
HomePageModel.fromMap(json.decode(source) as Map<String, dynamic>);

@override
String toString() {
return 'HomePageModel(name: $name, address: $address, dob: $dob, reviews: $reviews)';
}

@override
bool operator ==(covariant HomePageModel other) {
if (identical(this, other)) return true;

return other.name == name &&
mapEquals(other.address, address) &&
mapEquals(other.dob, dob) &&
listEquals(other.reviews, reviews);
}

@override
int get hashCode {
return name.hashCode ^ address.hashCode ^ dob.hashCode ^ reviews.hashCode;
}
}

We have successfully created the dart model class using the extension. Now let’s see how to make use of these methods available in model class and serialize the JSON object thereby accessing individual members of the JSON bundle.

Consider the below code as a fake api repository, where we try to return a response after 100 milliseconds just to mimic the network delay which we normally get while making API calls.

abstract class HomepageRepository {
Future<HomePageModel> getData();
}

class HomePageRepo extends HomepageRepository {
@override
Future<HomePageModel> getData() async {
await Future.delayed(const Duration(milliseconds: 100), () {});
return HomePageModel.fromMap(jsonVal);
}
}

The response data is then mapped to the model class using the fromMap() method created by the extension.

Now in order to access the individual data members we can make use of the dot operator as follows.,

    print(temp.dob['year']);
print(temp.address['city']);
Object? temp1 = temp.address['code'];
print(jsonDecode(jsonEncode(temp1))['postcode']);
print(temp.reviews[0]['score']);

Well that’s it. 🎉 This is how we can easily convert JSON object into dart model classes without writing the code our-self using the extension. Run the app to see it in action.🥳

Refer my video tutorial for complete guide:👉 https://youtu.be/IE4MsCKchwE

Get the complete source code here:👉 https://github.com/vijayinyoutube/dart_object_complex_json

Check out all my Flutter related blogs here.,👇

--

--

Vijay R
vijaycreations

Hai👋 I’m a flutter developer experienced in designing and developing stunning mobile apps. Reach out for freelance projects: calico.takeoff_01@icloud.com