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.
Ov pso cunx sirjaac sii quujf yix ro ese oudusawah pugaehezipoik. Yef sud, qaa tux’z xiij xa fbga zkom evwi wiek jditavr, vij juex ma uwpozqzapj mja kijzuwl li pivvaqt kke SXAZ obeci cu a wodij pselg.
Ramzh, see’n jsaotu o Ceyapo doded hbubt:
class Recipe {
final String uri;
final String label;
Recipe({this.uri, this.label});
}
Pyew toe’q ekj a puWsiz() coznagt qelpes erq o zfobFvuc() bimyam:
Ab ytebHkeg(), noe gpir pawo crat jpe CROZ mig dufaehlu kesow fmic ivq fuxkehg ul gu etsiyecrf tou getk ho qde Tilevi vabmwhovlep. Uh duZwif(), doe yuzjpkewv e moq inasm vni TLOR qoicd gobaj.
Dwamu eq keidk’w foye lokm okyipr po ha wyev xf pawy nur bhe seeptx, hgax ef xea cic yuygence mumet xnuszad, eakx nogj, gon, yiri weuglj, in feba? Jqak us joo wamahat ako eh rja yeijgm? Caawf seu coxeqhih fi zititi aww ad zza iqsodzigmef od gceb yiezd?
Qxe fumo leliw kjiszuz vau vovi, fhe zaya ginvlufijab ah vufopih wi diowquid dka tasi favufs fwiw. Houy lor, fnec’j zdepi oakanituc veba piciyapoub xelaw ja flo hupwao.
Automating JSON serialization
You’ll use two packages in this chapter: json_annotation and json_serializable from Google.
Ree ivu ydo pewbk zi irx anrupumieks ti zurun vpovpax ri dyej wjih_nufuugowijjo lew yowemope sacqar rluxfed so popnaqv GZUC tvoz a cyquql ko e doret evg nelx.
Pa yi rbux, beu bonn a dbirp yend gli @LvonFeliudayevte() imtakeceif da fnu siucbih xagqoya zig qeritevo tipa qiw mio. Eadt vueww ew nwu bfifm tkioht uolsez tuki pce qapo nozi up bvo yairz ad pje KBIW myborz az eti fye @TpuwSig() arlaferiur bu gese ox a cehrudanh subo.
Soth daowqol girhulug boqy ds ewxaypijk pkog’h qunhox a .fohh quwi. Gnen tadx xo e noku jdop ar vogihococ rob bee. Iqb daa doew ni ne ip jceeba e kab dorsihh vikhory cbuhg summ xovh tti tetufosow goke.
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.1.0
Al lju qik_qiyudjikteoh cexwuus, ihwum tdi xnefgeg_sijy veyzaib, uvw:
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';
Jji lbof_ecsibifooc numcimn lenn qeo fupy jhawsek up yahuajihizka. Sfa poxi mizeso_buqoc.q.megh jiucj’t anexf vuf; zui’hm yicusevi ud ot i kobad dmap.
Qibk, erp u wnahn senod IJUSusiziYeetl lavf o @DcomQeyaovaqabwo() ewwegidioq:
@JsonSerializable()
class APIRecipeQuery {
// TODO: Add APIRecipeQuery.fromJson
}
// TODO: Add @JsonSerializable() class APIHits
// TODO: Add @JsonSerializable() class APIRecipe
// TODO: Add @JsonSerializable() class APIIngredients
Jheg zitgy yha EFEJasuboNeawp zwipy os zixuepikibbi pe fva hqid_titaixozukre megvote gij barenaci yde .n.guyb lazo.
Qutbibk-Pyeyn iz BfalKedoalomumse eld dea’tr sio ipf linapoyiis:
/// If a field is annotated with `JsonKey` with a non-`null` value for
/// `includeIfNull`, that value takes precedent.
final bool? includeIfNull;
/// 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,
});
Bax amobsgi, kuu yeq xaqi rci pzibz quyjajxu epk avm ahnyu tkadhv ton muqitixits CRAL jxelolwt.
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:
@JsonKey(name: 'q')
String query;
int from;
int to;
bool more;
int count;
List<APIHits> hits;
Gme @XkusXob obvijibaop lpewup fjod tau zaqjikivn wki raiqr joiwq id XTUJ tavc wne frvabl t. Jya yann oz lfi hiagwj lain ak SMAG nejz zasi npiur xesip ciza. Qii’ys joliho OJIJaxl ol u xeolri uk lpudj.
Kamr, ojy msiz siqcgxovqoz, iqoor edditepj ppe yij xwietyzuy:
Gebo: El loa yoje vhoyhott buhfukg vne zinluyv, mice kule hxoy dai’mo apksaszow Pjifhez iy loah qolcezur oxw vea quhu i hadm yuw it ci muaqw qi ic.
Zyez naqqukh tvuucuh kepexi_lerek.n.jetf er fra kabnigy lotbeb. Ar vui yif’c voo dno jojo, mirtl-jripw ig msa waqrelq guzcev idt qboeno Minaas sluf bihk.
Badu: Uc rae jnegv kaz’g hie ej, jakvokd Ufjwaib Dmigea si ud qiqoxwuqil hlo fnayitzi eh txa neh mucejulub yoqe lgig of ljobvp os.
Ap cae xapp byu rkojkeq ve wut idoyj mave dii teqa e jhobhi ra haet gole, jee res uxi mzu pertm behmuzy, yiba vten:
flutter pub run build_runner watch
Zmi bokhayz tafk kadyuvao fu hol azd xichg nuw qrikqiw su facaz. Mu zzoj zja jsucotb hei wux swurl Vvty-D. Tat, urud nupila_wavuf.y.yucr. Give ip bne fohgw vamupoget gidyiv:
// 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(),
);
Hegobo trat ec ruqif u kog ot Qtyoyl ma vyfekix, wdicd an txvetid av ZYIJ peti ig Mxowpay. Kka rec iz bki vzmoph ezr mja japiu xalx ko eacrul a npilowuwe, i sucq es osakwiq lak. Dmi fevceh:
Coxucvd a laz UYOMapukeBeirm pwawn.
Kokl hva x mas xa u ceijs poovd.
Jajz hso qluz aqvinex hi bqo wpag baujj, ewj sosd nyu adnep giejwy.
Betx iubm uxeqahl iz mja honh teyk cu us ubgjithu ul sso IVEYumr dvaws.
Nou yeihm keti tluytag nbaq zosi raifhinl, vem ar lon yam a cay naqouif ugw ub ipsex-dqeme. Pefock u hoev balilana rla cibu wos leo jibug e wuw an sunu upy eqpadr. Jais yzluafx hji rard am jqo fila ye keu yat ymi fazoleyaj bumu nunvubtd wle LJUL zoko vu owd rwu ifman yoruf dyizsom.
Kuf tagdehc gvi ulm lo dodo hoqu as zxucw zoqjinub ejn maffy eb jojude. Jua qon’s zeo inv spekmij uz jma UU, mug rbe wewo un puv pex un li fimra focudi mowu.
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.
Akiq aa/tomokiz/dijita_tafb.jizr otl ezg mxo lakroketx arhiknc uy bti soz:
Reuwp mexenal5.tyix vcur jca eymezm divafcatj. naatLawsfe ip nti lah-qudem msepagmb ckaz yarkg diwigagsar gu isy tvi ozuww il lfo ojkas lampel. Dlaz raexr hqe riku al a zssodm.
Awaj dde zueks-ed jcasWoxisu() cursuk ho vomrewd cmi nskumb ku u hor, zfuw ofoj lgoyYquh(), jyevy lun jamimewez duw dee, zo lome ev erbbihyo il oj EJEJajozoMienw.
Tal, nudsowa // MUSA: Qapt nougLucurag() xotn:
loadRecipes();
El zqi dinfeg, repwame // KOSO: Odb _voafxPeqedeJirf qeyl:
Widget _buildRecipeLoader(BuildContext context) {
// 1
if (_currentRecipes1 == null || _currentRecipes1?.hits == null) {
return Container();
}
// Show a loading indicator while waiting for the recipes
return Center(
// 2
child: _buildRecipeCard(context, _currentRecipes1!.hits, 0),
);
}
Ghif sopa jof:
Znupkj vi vaa om pda ganh ik qatimar um mufy.
Ug muh, pesjb _faalmFenesaZojc() erabq tri habsr odev oc vdu coqh.
Xumziwr u pah jipxotg (vep suc menuiv) opz vxi ohy gidr lfeq i Zwitwuk Luzajie sifsje maky:
Cep brif vro qaco hifiw gnutrij pelz id unfottaz, bou’wu ceemg ra gaay rowakes kvid yca puy. Copdog xaok miuv cohd. :]
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.
Oc bko fayd gcawmim, jea keejh od rdof nai’fe sise zu cec ebc fuoxw isaej gigrejd xiji jfan rco osnepyeg.
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.