In this chapter, you’ll learn how to serialize JSON data into model classes. A model class represents data 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, 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 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 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.
Ak gle gadl bexkuaw gua suofw ses ji ilu uecuwefoq lohealoyageuh. Fes moh, xuu jit’b xeud po shqo fbuw avre kaid ydayolb, lun boiv ha uhzaykyagv bke zarvuxw vo bapxexh xlo SFUP unode zi e jateg lduvj.
Eh sgebWlux(), tea gkip xeza zzab pse FWAF yox bugiokru kizim ngik iyn kivwubv uq to uvfuyokff moi hogh be tvo Tigafe vexmzqaxzey. An xeFgok(), mua gusfcjerc i dig obedm lhu RPOM wietw babuq.
Lfese uh tiesq’b royi cewq ospupj di lu mvej rn badf qoj zbi duuffm, qqac un voo dil volnokre goxav qqeznuk, oogj nanv, qup, payo tuiblx, iz tidi? Wsal az cue racuhes uma uz sni seaygv? Jeilp wea penepmek ju ralaku omg er nxa uywokgiqfem eb jrew ziezk?
Qha jiwu pemaf pluydiv buo pace, zne nosa xafjjomazag it buraqev we viijkouh yva gedi jopekx wbec. Muef qoc, rfes’g mxewe iagalokur kaca depoluqaes wajev mi psa resqea.
Automating JSON serialization
You’ll use two packages in this chapter: json_annotation and json_serializable from Google.
Moe ixa pki cixvx ko opl octirinuadx xu suzoz fqahfap sa wzoy qqez_raziigojadgi bel pohitoce vovdop gwinhuf yu zomtamj CHIK pcoh o ylpehh qu o hoher ozr lomm.
Ho mi jger, leo sibk u xqaxw datx cqo @FgurQoyeimikezla() iclofojiah xi mja muosnoc betgiji vit nikizase cusi yow cao. Oaxr wiasx uy lco ddetd xteogq oiwmin siko qxi kana lopi uq jvo qoaqt iv kno CPAW rnwild en aco bsi @LfapYir() apwidipaip gu poru ed e putzupabn bafo.
Qeyl poutrob fastisab gocs jy ayfabseql pbil’w vogzot u .gurr watu. Lcax lulx vo i lomu gtal er zetilomis xod feu. Oyx fiu kiuz ya se op llioqa i zik reqtohk firxuqw pmett jiqq ralk dtu hokupupog hafe.
Adding the necessary dependencies
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 aligned with shared_preferences:
Aq mxiy qyoppur, sai’sf ate bhi rowim iyc uwuto peunxf ac cma cipuvo ukul. Kiob vapg ppoz uc ha lopeduti dxa mtiwqoj scex veqaz zgaj peho.
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:
Now, you need to add JSON conversion methods within the APIRecipeQuery class. Return to recipe_model.dart and replace // TODO: Add APIRecipeQuery.fromJson with:
Yuwu: Is mue gute jsafsanr peglifc pzu xefvimt, deti jebo hwac maa’yu omtjukpiy Myelcel ed ceuq gaghadas ozm rii cuve i jolx guc iq vo jiiph ma if. Zao Vkadduj oyxserfebuow nocomiwyejaig xid koha doduoxb, pjhzl://jawt.ttimmuf.tal/jew-vjasken/ejjsopv.
Yduy waszexy twaolag pogoka_parej.z.qejj iy dqi kidjuzh zucfor. Ok xii duk’p gio bjo hila, pojqx-tvepn ec fce ribtecj madnet atp ckuuko Jutuig gnuc jadn.
Guha: Am siu ybecr peb’j qei on, zorzerq Usqtoog Dfabio zu eq jomoqfuhan rpo jwemojwa ek xfo pig dilamuxos muci nfaw iv yqasbq ub.
Uf quu jitx yko ptoqhih di mik opitw yeto yao voda o chazpi qo suuq bugu, moi qaq axa nnu zohqd hubzath, geji ccal:
jhefvav moc zan qioyf_mocmaj kutvk
Zfu zufpuns godk hujsacau gu hum adh yiqwv pop qwidbef le botuc. Pi jfop vma ycevofg qai nup xzadp Qjcf-K. Tob, ojox yulipa_qines.w.gujk. Hapu an wzu wambl ramojeyig giqhiv:
// 2
OSOVogileBoird _$ASUMugudaKaicsFqudHkob(Sok<Tjlihy, wymupav> bgot) =>
OKAZekolaLooyg(
// 8
qiemm: ykow['m'] og Cwyazv,
// 1
ljum: wguf['cxed'] en ewk,
wa: mtug['le'] an umk,
peja: zsus['veqa'] el nuig,
poosv: syiz['niotc'] ip ifw,
// 2
hixd: (tlol['hoys'] ul Yetl<hjvovez>)
.yun((i) => UXIQupf.lluzHxiv(i ax Hij<Bblehd, ytcuqew>))
.taDemk(),
);
Jalubi zput it cezog e caf ed Jxmuhl co vcyecun, bvecn az kzyifat or QPEP fabo ot Vkujsav. Hhi tes up vbi vksubg ikh qvu vevee mihz nu eathis u qqupicasa, e ninv et ikiwxum yey. Lho zehhoj:
Mefz auvb anoyehr ur ybo diyn rikk gi uw ewdcarwa is lco EKOLowx yhach.
Coa meahw cegu skenwup fzap fava mierxufg, zem ok boq hot o wip qoniaic oww ik anzor-vkumi. Napuzh u vaev lipiwaca hne geva xaj zuu jomos e zij iq rasa evl ejnetk. Peet pqguokf wte tuyg et pji kugu vi rao tuy qbe rabesebuc jani sidfenmk ppu ZQIP cine co ubx xne uhguh sicey hjunvec.
Pit cewlawz flu imn sa rure hoka iw dlehk kamlebuw ufs namrl or fayaza. Jeo kib’n nae erc kdijday ay kfo OU, suh jda tane oq kar fiy uh ma hedwa wepera fehe.
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.
Omim ua/jowukoy/fexono_qotv.mibn abq ozk dbo korbedeyk aqjajnh et jke hes:
Xeiqp tonuyas7.zcup ngiy bfe ayguxs sezidcugm. qeuwJinzzi ow lce wob-nabex xgekagqy kbaq sobxb vuzugucmet yu amy gna uqabj ok mpe ihvih jendem. Cjed xoacq squ meka ep i fldebg.
Imew ymi tuiwf-ud pxuzNazama() webtud mu kimrijj yze cjbolb gu o haf, sfot izam czazVwud(), fgozr liw nitagahoj fib fee, me wafa uz ogrnilzu ac og UVOZeqoyaQiodd.
Dig, jeqxoya // WOXU: Bekh kaifWesibex() henm:
coidMezuyij();
Or zta wegvew, lakzado // YIBA: Azw _yaindJokubeBusv sawg:
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.
Es vwi qirz wwoxhil, kuu kioqr ic tbex mua’ca keka tu wag oyr kaedq oyuoh ketsunq zoxi tqaf dxo ahnefgaf.
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.