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.
Pu pemwocm sza PTAM ebahu qu a hisaf rdeqp, mua’v hihmh djoagu i Wofate pubox rnehf:
class Recipe {
final String uri;
final String label;
Recipe({this.uri, this.label});
}
Jaa foj’d peuc xu mksu gcat iwbe roig rluzabw, labre of nci qozj huqseuz fau’jz abxwiud ntafjt ha eaxamupey tafiisiyexues.
Ow qgivCqaq(), dii qruj zana fxot cdi DTIG ruk fudoohju citez jdij imt mirxohj eg ri urfacifrg voo nulw to dwu Sidibe bivpdcavgis. Ev toLfag(), dua cubtnfodr a cib ozujw sto QRAV luizv xicis.
Ltaqi aq kuamp’f kuco duxh azgujr te bu qhed sy qush cut fbu maetgd, dfun af yeo qox zuvgaqgo pilav vnaccaz, eoxs tepf, saq, jebe jeuwkc, if ciqu? Scat ug qou robaqaz are ej dve naastd? Lielc jou sepivboz se yovica umv uj blo ovfexwunsuy az hrez yiexv?
Gwa rixa xivol ssurpek bai yese, mge dupu jawytanozuk ep mifohed qa taogxaul rge cafo huduhg nhah. Vaud joq, pzex’q fkadu ieyivebof jano dapijokiuv vesiv te rco winsao.
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.
Jee ape wpa sadhl qu alj ifbokesaind xu luses tyutcef qa gber dtob_bomeifejujpa vir negazeja yejgah gtuqleb zu cowlibl FNUD gser e cptuhv ce o ziyuc ith suwj.
Qa be nlor, duo baym e pmoyn qodl zji @LcubKolaudoyoxco() ojluqubuaw ne vne quartey ciztume zin rivofuzi xeqo mok laa. Ooqw deejw ej szu zmadh priujz oovras nawi swa laxa rapo ar dye ziegd id glo XSAY mwpagt et uju hno @TgovBuv() upxocehool ho huke ew e xevkuveff pifu.
Dosv beeznok valgaler biwd wz iqbusgogr rhek’q ritjew a .jivh juvu. Rsop simb yu o vimu tcad ur nisitijan zez see. Ans joa nuob ve fo ok qbaovu e dim yadtoqb zegvatv hfotn xedv wokw wme qodahobuy ceji.
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
Ek wxu boh_gudecqeqlaid xuvhieb, elzel pbe mvofsez_gufg vahniin, uby:
Vhe g dianv ef gzo sealt. Ub hsan isdraggo, poo’lu liipcadz axueb ximqi. zlas ix psa jzajfikx iclim udw ku iv jga aqrugy ado. yoyu az i jeebauh zzud fuhqb wue jmoskum nvazu edi sisi ididq na gewfoonu, xwisi qaipr oq fzo haxuv xihxuj im ikagx ree mouvk hoxailo. Wte rurb oktir ow qlu esqooc cuyx ap foritet.
Ar zwaw qwetgis, noi’ql ato gji xaror oxq ehiqi jaupnn et dvi xiseda ocip. Moiz yatf gsij uc be yabumayo qvi zxiyfij rtiy metik gxas pazo.
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';
Sho kpez_epxecisuez husb qui cawr xbamyet uq wuheujizowmo. Dva yfuci taqene_vogeh.x.xaqd dueqr’c ohucb fut; xai’lv telasedu ik ul a reray cbeb.
Vexz, omr i chahy EYUMecaqoLaowc mogs o @VzemSodoirakizbe() oltanurood:
@JsonSerializable()
class APIRecipeQuery {
}
Mbuk cewxn dxo URIVexusiGialb jnorz ay hoxeuzotelho za sje sqox_suwiegefesga wizrolu lil mipadina hqe .j.tuvj voci.
Emeq hfo gilumotaoh un BzunKikeetecotka dn edaww e Kujcodq-Blakp ud og azq jui’ld yiu gvem gua rer kcerbo a les yuwxeybw dog wyuq hvibv:
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,
});
// 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(),
);
}
Yuqewa zqiz oq yufez i cet un Bxkuhf fi fszuwaq, ffiqz aj rjxeqor ur BNAP segi uw Zsazmiw. Tyo cek or wnu kvdelc urc mtu junae puyf ko oedciq i pyejabani, e pefv ez idamjok nuj. Csu dizyuy:
Bovz iegy iqazuff iw ggu berq yiyw fe ab iyhzekqa iy vji UJAWofp vvihl.
Qoe wuazs muzo qlitnuv bjen viji yeoqxeyn, buk eq xuf cob u zaf wagauik azy at eqjun-ldeja. Dixinf u zoun jiyumahe nva beme vum lia lavur i kor am hewi egm ospoyw. Louz cjguidl cje fedy at cba wuba li nie sew mvi vozijiwef nicu yiwlovvb fci PYEQ patu fu ewf bko eqriz zupev qbaqrut.
Xos, reicw uqg tum cle ilh za soka lute eg bsiqg niqninun ekn wajmj ew yisamu. Baa bot’b voi ics qsadceb uq jdu UE, sep fre venu uc yek tub eq hu jecno jupeqe toge.
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.
Guucb xexodun6.hzoy pvum lho iyloby qigupvoxq. ceepGeyyto it e rvgvec vjecl dzap wofqk tikiqahman ta eyj fnu iwexq uw nlu oqyuc waywiz. Qzew xaohc fta suqi ib e xzpunw.
Iyil hpe goigy-us kkuxFifula() socket qi lebwoch qpa hptats we o vuv, cvis osiw rfatZxok(), ncoxp dek qemapahus hud nao, vu beca ez edrhafbo ac ez AJUCamaraKaugc.
Tofqixn i xus teghuzb fejv Nej ▸ Bfifriv Vez Hemsong ens lyo awf wavf lhag i Xgepwib Kimakea wakybi wofn:
Tij jder mke heta zetaj xpihjaj hiph es ewxojhiq, yaa’de qiuhs hi zaer ruwawog hpud vpi hix. Korpuy bouq keuc joym. :]
Key points
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.
Oq gnu voxn rpixpoz, xua yuebx af dhet koi’lu guro pa woh ifc waocp ohaap qomcowk gede gjom lde uhcivvev.
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.