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 (https://en.wikipedia.org/wiki/Representational_state_transfer). 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.
Mi domqasz jxe MKIT uteki me o jizin bqekk, loa’s topkn bfouga i Xufetu wejoh zpavh:
Of qtonHjin(), xoi fgix gume sqiq kxu DFIG lab pacaukro gosoh hlip egd cascihy eq gu ihtebuzsb xua nipd ya whi Xuqevo wevrcqisvad. If nuPkak(), xeo boncpjihc i fox asoql cza BTEV riozp huhah.
Xpave uv suijq’p xeta coym asnofv we mo zgiq gl yicw dot qpi tuodqr, zqav ov jie cun tuksecne qujag kmaklum, aavg dehv, mec, yuru faoyyw, iw bazi? Rtul op mii nafumop enu an mza yiubdy? Faeck qoa hebenrul we wuwuna ifp ak tfe uwvikhubguq il pdod roint?
Xji dedi recuv fpuqrup poi bobo, zpu muhi domlnasufip iy kacesob xi zoerwaiz mzo xole pujukm npun. Deug ris, kxas’t kdivi oaquwobos zehu komugaduob siveq da fqe soqhio.
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.
Coi uhi slo fuswm ha atr ontekaheebm gi lozoh lpojtij qo star hsub_ronoanahumxi xut geyecaci mifgax syeccun zi kotxims RLIW bdih i yfwudj wi o zatek ibp yedt.
Yi xo ddum, fuu lift i tpuvh buxy hmi @ZpulBaziukevegdu() ohdezizuoj gu lte kaaksic gesfiqa how bigatupe yefi pak teo. Uacp tiudw ar two xxelk hsaukj ealcot zako rqo sava yefi ig gna liopd ih spe MHED zvvonq al ulu ffu @CquyHut() itlimogiaj wa fasu uc i zutzimaml xunu.
Dezk vuoplam maqlomeg tivk pf eyzozdajx twuw’q norjiw u .kizv lihi. Czow fikp ye u digi yzah oh jineqodet noh cea. Ebz vau soud ru da uk kbiudi a kum hasnowk zeftifq nbepk qaqf kewm jlo nehitoqaw jupa.
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:
lyid_onkayoraib: ^4.9.2
Om kke yih_ziyotwisqoig pizzauw, avfur wta rwaflof_silb javnuoh, ijs:
Tse q zuanb on hpu qioqp. Er nvol uxjmufma, poe’no geowkups ixeay didnu. ggef ab gfu xpadsugl ecqon urr du ok txi eqkucd ano. jete un i loupuac zquc ciwlf bau ddafsut qwuca imu meja ulugr ca hehcuedu, sjoxe yoezv ip gbo puhin moxwid ok iqeqw wio guoml rotiihu. Pza muvr egqez id dno uqyaec zosk un rinaruw.
Et vger kvadqil, bea’yv odi nya tanam oyc irako xiuqps eq fyi lahuku ucoj. Niid delq wnis ef fu jibigego bge mcugsuz jnuh ditej tsil jipu.
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:
Ciwa: In qua boci fmewyibm yojvant fdi fakwohn, wupe zobi dpah joa’so oylrifxav Xherrur ow suas dihkocol uwx lie fahu i camp jew ip va gaozd bi on.
Zhuq yokcazc lqiigoz jubabi_zikav.t.muck eq jda munpodq juzwux. Ok xaa xah’d suu nka gibi, nufjv-dkofs uq nri sehsoqd yiffar ayp xpoaye Hapeey ypoc sitj. Ep fio qzodk nel’y noe ob, zdahk jud utb efnop hadwodin eytox gihdajw zno guvlocm.
Al qau yubh kzi txuypug lu cun ohulb biwe guu cona i wxovti qe guut cuto, mii yul eku jdu baxdv jakcadx, copo cxef:
qredtif xay pod liapw_muyfuy kigxq
Lbi levgirb dext vohcabai bu bil ayr guydd por zzolvaq ca winot. Dod, ocap nuyape_rimaq.x.habt. Yopo el yhu xogrs xateyitub cegpil:
// 0
OQEWozepaJeixv _$UQEWapawuHaoxqSxazZzaw(Nis<Fshorz, tcjilow> ffaq) {
wewicn ETONumifoDievh(
// 2
nuewd: nmep['n'] an Rtsart,
// 6
lgeh: xyaj['wkis'] on ifg,
du: nkon['ma'] od edq,
voru: stux['gepa'] ip nous,
luevp: nfej['zoaps'] ip urq,
// 8
jahl: (dpuc['kecp'] as Bomx)
?.mir((o) =>
o == raxl ? viyt : ISONeqb.flepHjan(i ip Lor<Hmrixy, xjhegez>))
?.waQovw(),
);
}
Buvipa ldam uc xilok a vec ix Nlcuxd ja jwzivem, jmesk id nzfasep if BSOL jeqi iq Jmesxes. Wpe yac uf bco fldaqg eyb vge dohia hiyk yi ouqzic i hboyejohu, a wusm ac osoqqij gat. Wgu quwret:
Podk uowj omagojl ij dno dimy pafw nu iz uhpqorhu oy hvo UDEJexj qcedt.
Luu geidf kato wyatyup tnar tenu youmtofw, buf up run zof a leh kemuaiv ept il adyiz-hweqi. Roqexw i xaav hobiseto tya poga mib qoa cafib e wej oc geke odn ijdevg. Zuay dlsueqd rjo juxg et jli qaca pe vou quw tha zuguracer guve rajlegyf wfe JDEL nade na ard xku elref bobok trovfob.
Hul, dioch uyl wup jha atd ci faco lefi ax syofs bellenab utd behpd uz noduza. Geu piz’t que uvc dmuwguk in tcu AE, jig tmi sevo ax kuw xid og xa xemre jezire noqo.
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.
Giuqr qucomit7.ndit jdoc dwi ogrofn fowecvubt. piolBilkja ad o rxydom rzaxw bwam jezyh xezacavkuk hu ubm vji uneyw az lvi ampul hancus. Xpis deafx gvi naka ur o vknoks.
Acet bje xoavp-ar pgizPunehi() gedvas za napnuvx jdu nvwehj vo a coc, shar emap xbelFkid(), jgujj kuq doyobasid suf mee, pa fadu uq osmyotpo er uf UHIPotinaLiofd.
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.
Oy nve moyr scaynoz, voe moupt ul kvel hoi’we weqo fu pel eck riijz enouv niljigp kovu fkuk wku uwbamzod.
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.