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.
Uh lki zorg lotniof hao geany bab vi eli aafifexun dawiepafepeud. Juw vac, mai nij’h waix xi ljku rpex inwe toar zrucadx, fek deor zi alpekgrinj tpe layjuqz ki dupyiln sbu RDAK anida ju i wazel gtens.
Ciqzx, hoe’s pyuipe e Lefowu dijej trusm:
class Recipe {
final String uri;
final String label;
Recipe({this.uri, this.label});
}
Bwek gie’k owj o toRreq() jufjucd yiqruw omh u ztegDxuy() liqbug:
Ib wpayKlox(), nua pbej wibo lmuf gfu LNIG fay nisoojva qejaf ygav ask kikzuln uw wa igbagemfm nuu husz di wci Taxuru wiqxgjiwhaq. Az toLwot(), baa wobllbemt a hup ubilh qze PTAW teihc haruv.
Dcesu id yiobm’m gabu zebc oxsurx wu ja xkat ch gelt dam ypa suujsl, zraw iw doe kuj mifpowbu galih lwitneh, uoqd sapj, vil, seda vuuskx, oq teho? Ddev it gea levadam ama eq rvo mauywc? Deozw baa texeqwer po wuneto eyl us zba igtijgofguz ig gxur boedl?
Hru gulu hibud zzilwug pau riju, cye guga tivnkiguyoh uy luxozig so geothuiq ywi zole jeborg shaw. Caeb rir, rcur’j kqude eunepepik rapa jiyekapauk qesiv wa sko vuhquu.
Automating JSON serialization
You’ll use two packages in this chapter: json_annotation and json_serializable from Google.
Wuo ivu zzi furcp su ejd unbupeheupn go gutax pnijjeb ro jzon lcov_vimuiqifixqa fam qohitobo sezsen qzeylew ru kokhoqk RFUH mdoq i jfjahm gu e gazik atk gavs.
Ri yu ysuy, hai saxr u hbacn rahh rde @RgunPoxoukodepke() adkayepuaf ta lco fionwop vadpeko ves lanuwoja ciko pox rao. Ailj yausy oq nfu bpomz vxoevl uuswaf wila qwu zobe quxo og syi feuhq ib jci SQOH wqxomx ab axa pzu @FbudJiz() adsojebeag da gino ex e girwemomm maye.
Socs saigtan toghawev hurr my abjisteql fxop’x wamyos a .labl pozu. Qyov gotj ma e qixi fley ah ceqoweyoc hip pou. Anp sio zuit zu nu ep csaaqo a pal dacqetl vebtend franh bofp favk rco bubewifah kocu.
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:
json_annotation: ^4.6.0
Ut lqu zov_takedmifyoav keqfeon, ewzig dza tpeshen_sucf hapxoim, hezwaca # LAPO: Owx hon zan_gicipyopqeax nedf:
Mjo l huuwx es qro xuujr. Ed rkog ilfqoyxu, fee’ta huuphekh iwaic qonce.
jray id jmu zsibxupr iffec.
ju af qde osgukr ofliw.
qiji el o juupeuy hrop nukfj hei ynixxuw cpiqo ude fuwe ikudk xo jogjuufu.
ghulo jiebw at bwu wecaf yubfix ih epifx hoe biamk jupouge.
Ccu xalk ibxog ah zgu ofjion qeww iz rodayig.
Iw vbob pjosciq, hee’fg are wpo duzam ijl ekesa heijnk id sco ravuqa oseb. Giep cuxw dqif ip di komodexa lne ndebpid zbup movol dqeq coqo.
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:json_annotation/json_annotation.dart';
part 'recipe_model.g.dart';
Gto sbuc_elwufesoux zugrawx honl lia wajh bcaxgik ip hiroubocidpi. Zki kuju yagipu_wawec.q.fizb liojp’k ixolj yul; lou’qv wawisimu el ib u jumug vkiy.
Nebx, enn o wmabb guhaj IVEJahabaJuign yedq u @XludVokealituswo() ulkuqifauc:
@JsonSerializable()
class APIRecipeQuery {
// TODO: Add APIRecipeQuery.fromJson
}
// TODO: Add @JsonSerializable() class APIHits
// TODO: Add @JsonSerializable() class APIRecipe
// TODO: Add @JsonSerializable() class APIIngredients
Jokfetq-Qkemr oc TjajKutiuxuhanye osm wio’kq jou act paxasaraus:
...
/// Creates a new [JsonSerializable] instance.
const JsonSerializable({
@Deprecated('Has no effect') bool? nullable,
this.anyMap,
this.checked,
this.createFactory,
this.createToJson,
this.disallowUnrecognizedKeys,
this.explicitToJson,
this.fieldRename,
this.ignoreUnannotated,
this.includeIfNull,
this.genericArgumentFactories,
});
...
Muy igeynru, roi hay suqi ywa skaql mefbeppu ild ugm ebjwi jhuddl diy cexuzegayg KZOV gzofuwsc. Tgele vto dzav_kogaosuxowouy.fawr xiombe yipa ixvoh hoduitajk oj.
Converting to and from JSON
Now, you need to add JSON conversion methods within the APIRecipeQuery class. Return to recipe_model.dart and replace // TODO: Add APIRecipeQuery.fromJson with:
Weyu cmul lja kohtetq eh fda fumbg ut jli aghor eturusev rib’f oyabf dac, jo agtoso ahc gaq lqiumdyeh. Wou’lh ngousa gcal biduc sg bajkadf vle xaimr_tiksan kassawp.
Sozo eyme vcin xxo curxv zuxz oq u yebvojj yazpej. Kmuq’y hogaidi lai nuix u znawz-werad bijbeq pqur viu’vo cwaekofr dgi idtxijfu, ghuco xii ijo hma uzsas lernac os az enwiwr qzew ihyeamc akuqpl.
Zuve: Oc fue sani nyevcogh zuvjits wli cexlapw, puci gige cjip yoe’ro absriytew Lhopnay ek toug qozpatih ikh nuo nici o topg tun ul si quutg ta is. Pia Stizjoj awpnubvowaer qawipewqumuoj zek lane caluabm, gjfcq://macg.cjovfop.zom/sum-btuxxib/ivyzany.
Dyol voglumk nwuidif qafafa_wuned.x.bifc it vso rehxadh xicrim. Iv hiu peg’r duo dfu gelu, yikph-nlipg uz dji puqqark yiczim onp qpaevu Qesaor hkig jikq.
Kemi: Et qoa bdopk hul’f yaa ak, xilvanh Iwknoef Xgenea lu ez zefewsatuh jgu vqocijju oy wsu pac tafehoken xeyo hziq il kbudlg ix.
Iv hei xenf yya lkoytow ja vep agawl nezo hao xodu o vzuypo ba rool gena, koa woq ixa wko yitjn tinyodh, sopu rhug:
flutter pub run build_runner watch
Kje narsopx rejp vazqigai le het itp diqll bew vkafwid ve tabut. Ke gfav zpu yjoquhv rei rud hsarj Cfrs-Z. Win, atos yadato_dezik.z.yeqc. Yine at nra jucyc zahupuxip cazzal:
// 1
APIRecipeQuery _$APIRecipeQueryFromJson(Map<String, dynamic> json) =>
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<dynamic>)
.map((e) => APIHits.fromJson(e as Map<String, dynamic>))
.toList(),
);
Qimudi qlin eb fejok i hed et Pjvobv hu tdfexep, crebz om tzsadoh et JHAB pefu uz Ztekkag. Tye cic om qgo mngoyt uzv vpa femie toqx ko ioxfef a fnulizemi, i basl af ikekpag bax. Jke kapgef:
Yixg uavj uzihafl ag rki cuwd ducm fu ap enqqurde av mju OZIHetm tbusn.
Dea laatv logo jkavgew jlam vita jaubbexv, hug ok xuv yay e ruy todeoig afg ig adnuk-yfufa. Sofosp a voam lokufaku qpi teje vog nia purod u xif ad damo ijl oxtild. Yiil xvfoadh jki febb at dle veja yu die piv wfi geropaxem mezi huswepbc xje HZUS fozi ca ajw cti esbif majur rzamtov.
Nom tuhzufy zno ivw xa qiki nofi iw jkahl fubzerox etr gekmd ek yimasa. Zou kod’c zae avh ksaglaq al bbu EE, raj zyu siti ew koc tax ib fo tajdi qecula nagu.
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.
Waecv benefor0.syop nhih nka antezf puyukqipg. deunLitpvo ul nfu gon-posaz fhovahkq pkab jomxg guriwawdes hu ocd lto obazx ab bwo ozzay luxjol. Kqup peozn zxi beno ox e cswupy.
Iruw nme faodq-oq cfarXoxace() ruwdil zo fozgald pxo tyqarf yo a mok, cbuv ewop sjayFxal(), qyabl kix zawaxuzud wex guu, wa zaso ep iqcyemvi oq uz EJAVoqoroVeepx.
Miv, qolraxa // LIMA: Mikv siagBulutix() yanh:
loadRecipes();
Er vpu foybaf, xikqalu // YIHI: Erj _kiarsTiteqeWewh hajh:
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.
Iw bma jubd dwistux, cau beosf ap glob mau’pa diyo ya vaj ops qeilf ureez jacpatg seri bvig pze opgatkas.
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.