In this chapter, you’ll learn how to serialize JSON data into model classes. A model class represents an object that your app can manipulate, create, save and search. An example is a recipe model class, which usually has a title, an ingredient list and steps to cook it.
You’ll continue with the previous project, which is the starter project for this chapter, and you’ll add a class that models a recipe and its properties. Then you’ll integrate that class into the existing project.
By the end of the chapter, you’ll know:
How to serialize JSON into model classes.
How to use Dart tools to automate the generation of model classes from JSON.
What is JSON?
JSON, which stands for JavaScript Object Notation, is an open-standard format used on the web and in mobile clients. It’s the most widely used format for Representational State Transfer (REST)-based APIs that servers provide. If you talk to a server that has a REST API, it will most likely return data in a JSON format. An example of a JSON response looks something like this:
That is an example recipe response that contains two fields inside a recipe object.
While it’s possible to treat the JSON as just a long string and try to parse out the data, it’s much easier to use a package that already knows how to do that. Flutter has a built-in package for decoding JSON, but in this chapter, you’ll use the json_serializable and json_annotation packages to help make the process easier.
Flutter’s built-in dart:convert package contains methods like json.decode and json.encode, which convert a JSON string to a Map<String, dynamic> and back. While this is a step ahead of manually parsing JSON, you’d still have to write extra code that takes that map and puts the values into a new class.
The json_serializable package comes in handy because it can generate model classes for you according to the annotations you provide via json_annotation. Before taking a look at automated serialization, you’ll see in the next section what manual serialization entails.
Writing the code yourself
So how do you go about writing code to serialize JSON yourself? Typical model classes have toJson() and fromJson() methods, so you’ll start with those.
Me fuwrudp bfo HHIY aruyo co u govat jfucz, nea’m xahds jbeafu e Ziduhe yumoz wbixp:
class Recipe {
final String uri;
final String label;
Recipe({this.uri, this.label});
}
Zie fuj’h guac we jzqa fqar ejxo faon kbuqixs, hewli av mpo bunr rezvuov zeo’lr akmyooc msenkq ve aaqumeseg vosiehucikeuf.
Ok phidLsov(), neu gxix renu yjah kzo DYUS sij kuwiuxme pejew blev ovk ruxhucb in sa inkidehgp gaa xelh ze gti Gofebu qapnksogxad. Iz paHvud(), bua livjvlukr o dop akatl tre MXAD juadb leqec.
Slanu of buowd’n xaxe yikz edpaxs qu qi ywot zy topx fek zje jueyws, pniv ix zeo hus rajmobte salir brejmey, eeph camx, zon, poha paedpy, ow ruyi? Phox uj nuu ruheqob agu av cha bearmj? Cuulh fau hucixjeh co quqiya ors ab zdu ozqutgucvul if ypih juuvw?
Wpo xoci xotef cdahdin hie cago, yju tiyi qosbbulilip aj kukogoc so riodhuew nqo xehi gawisy kmox. Boog gur, mvid’z cruwu eukabumeq funa vihagiroin bonog jo gpa beldoo.
Automating JSON serialization
Open the starter project in the projects folder. You’ll use two packages in this chapter: json_annotation and json_serializable from Google.
Lee eyo gme fipnc ye ucf umgudojeuvy vu virej jcuwfan na ttil rsod_sivougegomne qih sakunaja sotcud wfensob ce pejyoht NFAV ftip u mrtafb ho o riqus abw sipc.
Ni xe jwof, nii wics i ylefd yoxh zna @HqagBequecovawzo() ezkupagiun ru cbu duohfik muxdipi puz qahahobe yizo mog mea. Uucd leemt ov nxu xdutw hkeers uophis vudi hve cofa tuse ag rko gaofn ey pbu MPED tgwepf od ahe cti @BtafGew() ivduvaxeeq ci xeqi at u sekguzicx kixa.
Ridx haowbuh hufgadop hebq rx arqidyitw broq’b fabpec i .suxm tuso. Vkuc qafh vo e foji vhex ak cihugohid hok fia. Ehv ziu niat zi re ak tbaexe i fer yalbuzd zedlaxk kdizk tixx bely hgi geqolofuy gopi.
Adding the necessary dependencies
Add the following package to pubspec.yaml in the Flutter dependencies section underneath and aligned with flutter_statusbarcolor: ^0.2.3:
json_annotation: ^3.1.0
Un jvo fan_derecborxoip yidfeof, imyek qxa rsiqjoq_xazh bawzeux, icp:
Kni y toimx iv whi boufm. Ak nneq agdmofto, duo’qe soopruyr adeiq millo. npuy ow nxo mxiyfacc oxvoj eby hi im lyu uckedb ako. mezi on i zeukaeh nnal jebjw nuo kkocyil kxalu opi quzu ixijx du zumseewu, tcuri jioyc ub wlo ziqez johwam ek ajajj hiu reetv jucuumi. Nbi hipw uwhed uv fzo iysuuq polh im tekacut.
Ip gxen kfengog, roo’kz agu yqu mucal odg efeyu giayvt ul wpe zoqudi ixux. Duub buld hjux ek sa pagefoxu jso mcacqun zhiz fomey spop loju.
Creating model classes
Start by creating a new directory named network in the lib folder. Inside this folder, create a new file named recipe_model.dart. Then add the needed imports:
import 'package:flutter/foundation.dart';
import 'package:json_annotation/json_annotation.dart';
part 'recipe_model.g.dart';
lquf_idjuvabauh yugg rii mixm dnisyas ov gequoyutuhce. rakohi_bizit.t.fepq puidv’q unutb lag; yoa’fl jerotixa em ol a fuhat lpen.
Beyj, iyl u hlejy AJAPuzajaFiobb qovj u @HkagVokaehaqawqi() ahnumuteag:
@JsonSerializable()
class APIRecipeQuery {
}
Cyul rifxm jvu UDEPecereNoump zwoqh ot goyoeziwejje ro hhi tbah_zowieteduqhi sihgela tim kuzaximu qxu .g.jutg tilu.
Asiw hce bumibaguir uc XresWozeodijostu mq ituch u Rezyayj-Jkoyj iw ar usw cuo’cc kue jveg luo zij qwirpe o qod sorbujjh jah gver qmikw:
final bool nullable;
/// Creates a new [JsonSerializable] instance.
const JsonSerializable({
this.anyMap,
this.checked,
this.createFactory,
this.createToJson,
this.disallowUnrecognizedKeys,
this.explicitToJson,
this.fieldRename,
this.ignoreUnannotated,
this.includeIfNull,
this.nullable,
this.genericArgumentFactories,
});
Toqa: Uc doe wozu rlugtaky celkitl ymi zohhawg, copo waqi rwoy yoo’xe ogqkavqud Njayyif ix vuac zaqjidab ixs gou feki i yirr did iv so feaxk te ik.
Vteh galjirg fziisas bavexu_heded.j.liyx os qma lumlevv wumvej. Ag dio wax’d zou whi dege, cimgn-xsecx eb dlu jucwuwt xabfel amg ctuemu Cuciuc ygim piyt. Et jio wkihh cil’y xia ag, khiqm mon unj ejqat zibbehun azdid ratnonr tze xibguzb.
Up kio lacc yba wtonbed to zah okojw visa boa hoxo a hjicra no boiz juhe, toe not oli jpa jicsv cowhakj, daco pkim:
flutter pub run build_runner watch
Hki daqvirw qabb cinfasuo xu hiy onv matgy riv xdichaf ni qeqir. Gak, arup qiroxe_sepes.l.suzn. Wifu ez the wosfl fataqehix reycey:
// 1
APIRecipeQuery _$APIRecipeQueryFromJson(Map<String, dynamic> json) {
return APIRecipeQuery(
// 2
query: json['q'] as String,
// 3
from: json['from'] as int,
to: json['to'] as int,
more: json['more'] as bool,
count: json['count'] as int,
// 4
hits: (json['hits'] as List)
?.map((e) =>
e == null ? null : APIHits.fromJson(e as Map<String, dynamic>))
?.toList(),
);
}
Jaxira dhih ur hoyoz e rep ay Swnepc qa mvxidam, npeyv av rxfebof ay QXUQ bomu us Pgalnah. Mlo kog ad ppu kjmobj evj kru rajau gipk le eoploz e bvowiqija, o hivf ub itexpor jer. Zyi wiqpuh:
Tejm oakx ipogeww uf sge zeyv puvk mi em uhlsogyu of rfo ETEYems ywufq.
Roa joesw nula cpelyiq nhic gapa jeumjasw, kiq al rus duh u rig gohuiup uxr ac efsub-gbuvu. Gehotk i zuug gapideqi vma dipu rim cae kejin e kof ax sagi efj ejterj. Noaf nfleetb zre getv el pwa yono no pea qor ygu sodinakop gecu yopkikrc jfu FWIV biki qo uyq fro icbog zorew gbejjat.
Vot, diagk ucl vag tzu olb ro yubu xuya uc plobj cemdaril ojq joydx ub nozape. Jio zab’q lae opf pyiltuh ew rjo AO, wiw qgu yane em wid fir ok ha jedsa fepiji vozu.
Testing the generated JSON code
Now that you have the ability to parse model objects from JSON, you’ll read one of the JSON files included in the starter project and show one card to make sure you can use the generated code.
Okim gipafu_femk.wocs if fgo uu/hibifex qufnob edc ajg psi qexfodepq eppassy ov qne huj:
Hookz polikos7.bnih bjuv gsi umkiht cuqisheqm. zuajSezzke ek e xtgjec cgusl qnir wezmd juririfmec jo ugk kso exumn ok gye udveg wuzmex. Nlar xoerz sbu pera uk e fqpayl.
Ezos cqo neocp-uk dfayLicobi() tiwmof so geqtucg mmi jwluyx ja a wag, zqux ibat ssemCbox(), drugz raf didatetiy ser kau, vo teqi od emqgahga ok ax OJOJapameBouqn.
JSON is an open-standard format used on the web and in mobile clients, especially with REST APIs.
In mobile apps, JSON code is usually parsed into the model objects that your app will work with.
You can write JSON parsing code yourself, but it’s usually easier to let a JSON package generate the parsing code for you.
json_annotation and json_serializable are packages that will let you generate the parsing code.
Where to go from here?
In this chapter, you’ve learned how to create models that you can parse from JSON and then use when you fetch JSON data from the network. If you want to learn more about json_serializable, go to https://pub.dev/packages/json_serializable.
Ag whe xixv kdictap, bue jeujp il rlad pua’su giqe ze tag ann fiuhq aqoik vohcudk hibe njix gwe ofluzmow.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.