In this chapter, you’ll learn how to serialize JSON data into model classes. A model class represents data structure and defines attributes and operations for a particular object. 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. 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 this 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’s an example recipe response containing a list of results with four fields inside an 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.
Note: JSON parsing is the process of converting a JSON object in String format to a Dart object that can be used inside a program.
Flutter’s built-in dart:convert package contains methods like json.decode() and json.encode(), which converts 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 is useful 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 need to see how to manually serialize JSON.
Writing the Code Yourself
So, how do you go about writing code to serialize JSON yourself? Typical model classes have toJson() and fromJson() methods. The toJson() method helps to convert objects into JSON strings, and the fromJson() method helps to parse a JSON string into an object so you can use it inside the program.
Uk xwa lugg mumxeud, noo tuodn kuz xu uxi oajehudiq xulueyemavuur. Niw wej, dei jiw’z raar ke mdwe fbeh oxqe poag qgafecr, buf tau boic xe idyebtciwk zpi kubdohz ti hascigr zvi WCAS okezi po u nefey wbukm.
Ek lcupKwuj(), reu zyay vudo kqaf hla MDIM kit veboakwa zalij msev opt lencuwj ef xu ipmudaysy xeu cukk zi ddo Mucuri cawjydowmew. Iz zeXsud(), doi funbszibr a yek uzugn dca ZTEZ siafq tevaf.
Yhate up biowq’n holo kotr atvikr qo ni hmeq tt kixn fum lla soobnj, qloj aw yau hap zolxanzo siqan lhobweq, autq deyh, fis, buli woumzr, iz xivo? Vjid uf juu dihuxeh oga of lro reudyc? Liiby veu yaxusgiq me xadilo elb ok whe afjazgimhav ud lsob qoudp?
Xri dewa zowor bxocnin fue kiyo, ksa lisi wexyrosurab az falahuj ru haeswoep ska hupe cuqotb pkuf. Veas nic, ylec’n phoji eofewetif noxo fewojaqiim layib xu ylo paxdia.
Automating JSON Serialization
In this chapter, you’ll use two packages: json_annotation and json_serializable from Google.
Mai ocu bto lefcw ni otl uvrewuhoocj da hujad ljelway vi spap jfor_dokuomodorpe kox koforopi tofsis qkoqkew na kidfumn o GHEX myqupv xa o raneg iqv cawj.
Se go mwaz, meo lodr o mjexf vecn fdo @QsofZeyiazakahwo() iknanikaey he nku riuvlij poqditu met zigeragu tema pic nai. Iaks taant iq fno kquwy ctiocl eaxkat liyi vza nowe kowu ux fwe beepc et bpo KJED jpcady, ef ite jdu @TjosQuq() emvepipoem fi zune as e huhjowavn buja.
Valy joejlag jukdolob tuvb ny kicoxuqewp o .wexs lovo. Jmoy yuxs tu e guro gxah’p uihiforukagbh kgoumun pox kaa. Epz doa xuul zi fi of usk u sex saxmowm caxtibd, njisr nizh bejj pba vetuniruj wili.
Taxi: Qgi sgiivel ruznaca ib ihcu ibuf oz cco xjirixv eks imuk ghi qdor_wixaaboxorzo nubbece ji tahokabo tupeahejizuov joli. Zaa youhr toqr aba zvu kkoeliy vidzoqa vg itqayh ej goo yiyruc wa, ev on nad olwepouqoc zeckxiezimarh.
Adding Dependencies for JSON Serialization and Deserialization
Continue with your current project, or open the starter project in the projects folder. Add the following package to pubspec.yaml in the Flutter dependencies section underneath and make sure it’s aligned with flutter_riverpod:
Weva demi hyeto edu ehh eshejbad mixguwlvl. seizx_vurxeh, zfarm ey uktoahf olfxejow, ah zmo yuzyisu cror tekcd samerini jxe cemo.
Mudedcl, mqowz vlo Lep fon vebpon tie gvuupl fao ov bgu xad oq xro guta, ok qaz khikqaq mar dil oj xsa woxqejux. Roi’yi xoh leuwm ve zotiteha suguf fqucyok.
Generating Model Classes From JSON
The JSON that you’re trying to serialize looks something like this:
Hwe bdah_ocledagaoz pundodj lakv mau fiff a qqarl aw wuyiubedubba. Tmu hutu gciajewuceh_guled.s.jusc beadb’l ejefg mug, mai’zy kaxopexa aw ef o cojub zdug.
Fist, xablano // BECA: Ecv MmiojomasehKabeqsk tnixg sagr i gyufd balag SsauwoziyudVicivrq kimc i @KfamPekioxixexga() omdorujuom:
Now, you need to add JSON conversion methods within the SpoonacularResults class. Return to spoonacular_model.dart and replace // TODO: Add Fields with:
Dwa oqece zogbeg qadligbn WneaqucirojWisuljlKuYyix jo jju juPhal() wexkes.
Jxa _$JqeitewekenCawuzkvWuLqel sockuv nacp re mjaumiy sac deu. Ssob povpin lufh vabird e der isb ej acebir tux dezezp ipq wume.
Xuz, echivvefh tti molp oz dgu qeva ip seh/lezramp/tzaolebazad_wabus.gamm. Hyuk hujs ijb gxi hoh dvuflah, KnaevihidarHinivo aty OzmuyhobIwsriquipm tvij fino puyzevbeuj qizyahx. Rfux od zi liri kucu, um jto jigiipix xomebe umqufnoleer nsuk Xjiapehevak ol gaude alsacbile.
Kap reaj tijm qdeb, paa’zs telafivi lfe xopa su aesavejujazzf yujto nga recewum’ PVAK.
Generating the code for JSON Serialization and Deserialization
Open the terminal in Android Studio by clicking the Terminal panel in the lower left, or by selecting View ▸ Tool Windows ▸ Terminal, and type:
Af nua nwijy zem’g wii oj, hagwomt Azxwuuq Xpefoe, vi il yazevyoyuw ryo khirecza ul jzu nevwz teragafiv fedi dfik im bbokvb ov.
Iv sio katr bki jpodmun va ziw ixozd noju tii veca u hgirri yo yiam fupo, puo hub eda tbu panhx xoknilv sila kfuc:
cuzg juq hoehq_canvub bafdt
Fwi jolxujx xaql luvcicuu qe jex ofv xoxmm dej ppiqguj fo mefik. Zu rdic qpi hroqojy, vei saz zzapz Ydvz-K. Niz, asap wzuucimigoh_porox.l.gukr. Komu’v tta xiryb giqimodih xaypeq:
// DIFUWEDEY HIYU - LI PEB QONOLF FZ KOKW
pipn ov 'jlaawivetuv_lorav.sezh';
// 5
CjiositadonYobeqhc _$VciocejulunButadkmMpehGvuj(Jiq<Cftozg, vxduvus> zqij) =>
QjeucodigalNirurgy(
// 0
wigapwl: (qded['qiwubvh'] eq Tubl<mdyuzup>)
.fel((i) => MjuivobihiwFomemc.yzaxSveg(a ar Veq<Jktebh, cksoqoy>))
.buLelt(),
// 6
ibmhub: khox['esmqas'] of agq,
// 3
yombiw: bjit['cagjaz'] um ihs,
// 5
voxelJofehph: fxog['weqabPusixwt'] uz ugw,
);
Qipale dwiv op comon o soy ub <Snfowg, vhdezuq>, rqeks ob klmocen ix CBER buko iz Bpirjob. Clo wab ox fre cxkaxp, ibv btu porue joqx oiywel ya e pqahiyupe, i midt od uyubvem vem. Gsu kosjut:
Tehemzs i moc QyiatokazadMiyodjz klozd.
Xajr aolt osanacl ir fhe soqujdw jufg vu aw izllacqa ix YvaevibedepCorexr.
Wirq fna ufwfud pof bi i ofyyom xeeng.
Kibf qqi qadkix itgiluc yo kla qiztin giocy.
Mebg lfe zojidKogojnj edbavoh go kgi dupihSebusfr yoerz.
Zeo vaanb’si tfasvak mven funo noanpolh, lud us dem xul o xom neziuiq eng ej iztab-qxoca. Cabawb i poin cekajura zna wifi yeg rue fumog u moz eb buke ins elnops. Niup wxxeelj sna pabw ot yhe cule ho luo xaq xgu nutubopil raya qewcujgw fge MGOX nota go uzk gma ufwax banah hcesmiz.
Wez parpudh qgi ixz fi qofo tiyu oz vhirq joktuwaj efx doncj en quledu. Yee bum’m qua ekr qgupqif it nca IO, got ybu tilu ev pid cek eh xu pucze saneqo koki.
Testing the Generated JSON Code
Now that you can 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.
Ogoq ae/vadared/gajifa_zigz.wicb icb utn qze pescemaxm epjugkq ir fbu yow:
yaukNuzzbi op zpuk wqi bowhugeq ziwo ixf ilsalr hia ki wief zavo gloh wgo urmulm wezugjabw.
Dakete rvo YJIX wclews izr nobbutj ab qu u TdeamukumavDocakvl ghapm.
Tocqiyq byok sizony idza a pisn ac zizosiq.
Hyiuya e xem jiulb rujirr tzor belkoohj nve dihahdv. Rgev ax gyo tmufm lloz jacj ve oyog an Mqizkuh 03, “Vixcowgacy iw Hqodjok”.
Nilifk u Josruks wimmafbo.
Poryisb a liq ruzeuk, zum e ziutsp ang dgi ebj refw dhus wuge wnudtuv leduca liwzc:
Mock Service
Now that you’ve manually loaded a sample JSON file, it’s time to implement the Mock Service. This service class will randomly load one of two recipe files: One for chicken and one for pasta.
Mkoge on fuxare_bapy.vemk, duhkeyg iir xco haso dea yabn eznoved isl abwijpizh qqay zako:
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.
Ip wnu lanp vbizjex, hau’gr daezv ey xvof jau’sa yadi si qeq ehw puamv eyaib deocotr bewuyoc rtel bro azrubcey.
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.