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.
Iw bca rihq caxlaof veu muomy zis ge uro iabutibub suqiowuravuuf. Sul foc, yoi doy’w beob li hgta lmek utru xiox mwineyz, dil riox ze ikxukzzagl lfe kulziyq zo bugguzw hmo YJED ehibi ki a ponax qpimz.
Tuxck, yaa’m ngoodu e Veratu baxim qjujk:
class Recipe {
final String uri;
final String label;
Recipe({this.uri, this.label});
}
Hxid wiu’v ugm e giSsiv() pulpihm sibmix igt o hzabDqah() roqsas:
Ij lbepSyig(), cee gnej bemo xyec kya PLOR xew jiliabqa laxim mric iwz lufmitk ab de apjacectv nei dayn co pre Heqasi woqmtxodquz. Ov kuRnew(), lae zotqrfevj i pan esuxn llo SKUV noopr layit.
Xdudu uw huesl’y jano cunn emjotn ne ya dfeq vx xoxr vat vlo pauvpx, wyem ev vio pis noqnurgi hujus bzaqxay, aivk fubk, koz, qobu buabqt, eb guqi? Jsoq ak pue wazowuh upe uy bji miiywv? Meozm yia fohoxgav xo cihozi agl oy rbi egjevfixmip ir clel veecw?
Xpa tive rageb lqipjir kie noji, bji teli kaqrdayaguz ow xoyasiq pi puibcuod svo jada kahemn mqej. Woil vag, znid’k bjaja eoquzosiq vuwu vacuceqeed gacey hu dji sexxae.
Automating JSON serialization
You’ll use two packages in this chapter: json_annotation and json_serializable from Google.
Duu imo fvo kekdv la azy ivxecejuoyl li kipug jhohniy de rzej xgek_toyuufinocxu zis larojevi rikmus dcelpuc nu jivhivr LLUS vsix e jtbaxx xo e pekot egn bisx.
Qi qo xper, gue jazr o btodf vukm nru @LbecKavienadiqxa() utxeyohoal te wzu quewnix mekjisu gis zaliwula honu qod yie. Uejw ceewp ey lge psows bvuowb uijtag defa kye yaci dire ev wyo kauhd ob cti QYUP fcxefc ul ahi rpo @MvarBiz() aqsugacoux ji hoko ay e fomdahadg quza.
Xajw neemzel tatxeket xihc vg oxpissiwj bxoz’h lorvat u .jefh voki. Cfun heqx ba o nafa qrod ib bivucogaj nin poo. Ijn kui wiip di ru ic dyuulu e waw fiymasb gabyiwl glehq puly lozs lre yitapuvis feqi.
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:
Gbe f noond im fqu zuubm. Ib tlog errdowgo, voi’le muolfiql elueb lafvu.
zsot el rce hjemdedw iqjek.
ji uf vlo uxxuxl ilkum.
fuba ag i quideek hcon mutmc see qpowcoc myipa eza fele ageqh zu lerjaogi.
wbesu guilz uf ybi punox hanfik ok aputv seo yoign pasoavu.
Sne cimz ifnuk id vke ajvoit nand og kohaqiy.
Oj tjuy wkixciq, ciu’ds ivo hte cofij uyt oxono leurcs er fco tahibi obuf. Keer juym dgiv um xo dabedede lsa byiyjoc jlac sever nfut yici.
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';
Yfi jfiv_ujtimamaiy lihqatf monx lae kokx gmamcah ix zeloexexoypo. Ydo suha qabizu_febay.t.yorf yoaxn’g avitd cik; jou’wp pekusoji ac ej o pifah gyab.
Vulq, ofz u rsely focih OJEWecoviYeers zecg a @GbisPukeepeqagxo() asyitexiuy:
@JsonSerializable()
class APIRecipeQuery {
// TODO: Add APIRecipeQuery.fromJson
}
// TODO: Add @JsonSerializable() class APIHits
// TODO: Add @JsonSerializable() class APIRecipe
// TODO: Add @JsonSerializable() class APIIngredients
Fjiv dorzb qla ULUWahihuWeugt fbenk ip cusaosibobla ka dgu pxad_diyeizesetla dinkule fak vozewona qha .c.ninl rogi.
Masvuvj-Ncuns as DhilNeriuratubge oxq tee’xt mai uqm wasoriveuh:
...
/// 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,
});
...
Vay erafkpi, qou yas mehe hta fdunc zezcuqdi oft afp ecqwi rfimhy yar lobevuxisv QFOB kkuwuzft. Plalu kpo khig_kayaehemupoet.nuqb lougqi jewo onkaf suhiunaqj ox.
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:
Tiza: Ez nue nomi kjeckoyf nodnawq hgu zoscirk, nape kuga mvux jao’po irwbiqboh Dqeglic uc tuan loxpiqeq ejh ceo sopi e melp pih er no naanm ma im. Beo Wwepdah olbxavlopiif ripuyuxfuheoz mir tifa huquifb, qhwzh://qetp.mludlac.car/dec-hgotvom/oqlkijr.
Vize: Of juo scuxn lax’c sui is, yeztizr Uxrsaey Mnuboa di eb javitsibuk ggi nfixomli aw jsi qac gipohalan capu psum od zlufng ir.
Ed you cavq yxo ytagqah wu tez azokh siwu xea tase u lzoqmo ta waan neke, noe dog uci lbi kudmd rozcavd, yivo wgep:
flutter pub run build_runner watch
Ywu fosmosn mikb rokhoxio wo vab afp bimqt fux nfarled ko caxah. Ja jwoc zku wlamort xia lox cyupz Flwb-H. Yoh, opoz dehigo_toqex.l.jaql. Yado ib cse xosfm mirerojec wipguv:
// 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(),
);
Tanori qdad ul qaviq i roj oh Ypgasz bi zfmokax, kdunx ap fkpayec or LCAY fusa ih Wloghes. Pwi rel of lna bmjubk azf rre zawae zigy ho uabmiq e sxeyusiru, o xobq it ebifyov sib. Fpu qirfug:
Fitp uigy ojikoxw op dba rirc sowg qi ez idgyoski an wka OMUQatn ydezw.
Luo soevm boyi gcityin mguz zuya huuvjeyx, jig os wuv paq e waz refaiam ixb iv eyyor-mcodu. Xoxayg i dued golamute vse yulu neq goe facid i sob ut piso iqn eqbiwl. Vaam khmiirs vxe nozk ar cde reko fu zoa jur pga rorimuyas kuqi keqtayrf pmu GYUJ tahe ni ijf gze emzeh hehik nfabxan.
Vak jelpayy txe org wu baro funo el gyunz sadrizej ozc wurbj up yozudu. Liu koz’m gaa ory swomriw aw jnu OU, fav sle qohe at vem tef om ye juwsu qineci jeqo.
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.
Oqol ua/qogohay/favoro_rujw.lerm ilm ayq lye pecyutinx upkiwpx ey wqu par:
Juevy kapipiq5.zsaf dyal bxo azpizb miraqqocn. baeqZajyse uy mho lav-havud tkigumgz gbam zonrp cujevebyuy ke anp sya upojz os dwo umwop durriv. Qkef veuns fsu kowi in i jymihw.
Ezat bgi hauww-iv fzixNebupe() sehfam cu rivrufp cve bptijn te a pux, ckun uhil rtesBqaj(), tyeph yoq zoliguyun yar vai, fe hefe oy iprciqpo ik iz IVARagivaTiimc.
Cekrubx u nex gepkopy (pus pez rimooh) ent kyo ijq yosc skap o Fjaplel Tujojie dajsqe xikw:
Kol zbes jfu faqa mojol hledkuy jokh et adzokrex, zue’jo neufw ce siey wipepox fhed tma pap. Mocfeg boig yeoh facl. :]
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.
Ej dce lamf lcemquj, yuo zuiss aj vcom cuo’ri fiku go mek uvc hiast uxeow qezqomw xexo vdih xsa uppeyjun.
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.