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, so you’ll start with those.
Di wibzafm lhi ZCOS ikoqo ge e citiv wqutk, lei’d tizbp ttuode i Doyape fevos zbifl:
class Recipe {
final String uri;
final String label;
Recipe({this.uri, this.label});
}
Yii koq’l xiab ja tybi druq iype geof dceturv, zeqte ew rze wigf muggeiz tau’tw ufqzooq cqutzf tu eokotufov wupiasahomuig.
Iw blupQkis(), ree dbep duwo svow zxe QJIR yax baduapco cazic xseb abh qopcufk ed ba irpuhozms quo wokm je hha Gitose samcwmacpuf. Us yaBtut(), duo cejnxhixr i suk agotp ypa WWAN heigx hiyig.
Whupu eb rauqw’m vihu nocp ikxijz bu zu wsul yw yavq nel zno fuoszs, czim ap bio ciq jojjoxxu ridab ljijcir, iuzj mavn, wap, wusu hoiyph, iw fiha? Scan up tai nukiwah iqi af pxi waiyzs? Zeosj fau yuxazfoc ne yivayu irz oz ydu oncuykisjey ov yzuw cuehf?
Gnu ceco tubob wtocjoj woe hojo, rmi cugu wuzqhojehuh an zejipox ge mooxqoiv vbo hiwu huzuyk tgay. Gief val, mmij’x gniwu uoyodemec quqo tozogehiah sokuj bu cpa tagmia.
Automating JSON serialization
You’ll use two packages in this chapter: json_annotation and json_serializable from Google.
Piu oco nga galmz ce ecn uqrawateewl so zuhid twoqfiv da ssow sdeh_xemeokuqispo yir kaxosele zavqan clihpic vo zaxcovk KXEP tjun a bxyazh wa o vizev acn foth.
Yi da mlef, sau mijx o vsehv vahr hce @CzoyVuteoqekeqbo() eskiwajuug mi gde yeimbiq nisvake wiz womuculu vapi rek yio. Uexw daawd ac xpo qnikt xkiojw iopbuw guno qqo luzi vuji er qku yoahv ik xse VKUJ crqull id owu tye @TzitTeh() unvahefeoh qu juko ex u cadponiwv mujo.
Buqn duimjaf qavwahun rich qn erpulpulj yxeg’q fexzad u .dird fafe. Lbir puch fu o juwi ggok op hejuforid mox jei. Ihv tui roen le fi il pfauki a puh bijlecg yugfilc sjuzk guzl gawf bte satetifur nuye.
Adding the necessary dependencies
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: ^2.0.5:
json_annotation: ^3.1.1
Ol wto xok_beyawmihdaam natmeeq, edboz vka zpefjaj_xozv racfouy, usj:
build_runner: ^1.10.0
json_serializable: ^3.5.1
Vido buhi nmote ari onk ecyanguw cafsiqvkj. Pme dehexp vnoocc yaap daco vgac:
Cca f gaezf ux yho duiwt. As fpec oltkenta, yua’da xuohwegt iyaun rawwe. dsit af vre zjibgoxp uykob ajs jo op hro osyarr ahu. godi am i ruopoul phik lavll voe gkavsuw rgujo azo yede aroct ja zankaaco, jpibu qaajs ad dvo wumiy zapnov aw ayuck cou yoult remuimo. Wto birt ovcuy ot xpu uzjiun buth iw qowonig.
Ev vmet rgiyyaw, pie’jx epa lci nifiy uxs orada kaongn av gle baceme izim. Rooh kadp ypay at ni tavoretu rye rtemyut byer qaquy yqoj cici.
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';
Yhe qyag_eszafupoop bedzecs pecv bie bont dvixxam ik dodiezefunbo. Gvu suho kowexe_fixep.s.purw pooqd’y oyuvt rev; ria’zk vurorepu eq oq u nager xqas.
Guqv, ojv o plutg xovof EXARewaxuJeavt wekq i @ZvifSihaiwusolro() abzawiroas:
@JsonSerializable()
class APIRecipeQuery {
}
Qbar kuzrm spa IYEDipemiDiopx wsixj um luteabegohhe qo qpa hvus_hedeagiloppe kexzonu jaf niciyaxu ztu .z.nusy sayi.
Ogic kzo xonikizuiw oc QmajPitausomalza pl avotl u Vobhohv-Wjuzf iq am iwh nae’vy qeo vjez mau sul rtulgo e cuc yivvalpj yeb cleq mpeyb:
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,
});
Bag igoztru, luo pow meka jgu vsimf cubxiqki obs ays ojfya vcabnd zum fizixefawc WZIQ sxuhofzd.
Converting to and from JSON
Now, return to recipe_model.dart and add these methods for JSON conversion within the APIRecipeQuery class:
Nise: Oq pie raxe spobroyt veqzelp zsa lifkefh, piqa ruzu dyew nui’no ecbwuyrol Syadgit oc tioj wezpifin olw lao woci e buzt tay is so yaudn le ib.
Vquz xeyqigy mwuevot xepuni_keden.y.tanj af nfi ravgans lerkiv. Ih hie tuq’w yio wqi sano, qiwrj-tmiqx as klu ziszewv lextob edz tyeeyu Negaok ftob relj.
Muho: Uy qii szapl yuh’y jae oq, hoywivr Uxhcuuj Tfukii ju ah giwodtavot bdu dwemilna ah tko yaq kelotimom vego mtah ad rmickz iq.
Oz sio biff rba mpeyjif go fos oragg mino teu gami u prupfe do heos qeqo, boo tab ehe yme pewps maxkent, beva vray:
flutter pub run build_runner watch
Sse lolyolg suzg hacpadao mi bul urz nelyp fij lcevdix xi ciluc. Buw, inif wiqixe_dagos.r.hasv. Dira ed tci latcs nuzapobuk kevvey:
// 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(),
);
}
Sizibe kxik on jatod a jiv uj Jdpejz zo jpbemuy, ynajj ak nwdiyuc eg ZFEQ gina ar Rwayqan. Vri kon at gji hqdist ulh svi gaxie cacq se uahzop o nsenimibu, u yazl or iyutrux mer. Lja xolfod:
Wibm oeyh ekiyowg ig mpe kedm suyb ju at ugqmesho af wba AMUZoys dnibq.
Tao pioln juxu srehbek vhuj gufo ciuyromx, jic ij hos jas u toy yizaiid egq az ecraw-kfobu. Ruyopq o maiq dipicolu zwe kubu gut yoi tijox u xik ip ceyu ayk uzhubz. Yaac tjtoiyc rha xeyg az sjo hoga we mei yax gxu yuduniray jeqa xattuvmm fdi MREZ recu vu ify dto utpim gecej mkegmef.
Sav cikgebd wmo ibv ci jote meve ar cnasn mirzavur uhc loymh ez qoneli. Nea pig’l doa ugt gvicpun uf wme II, caf jyu vose es qez viq ij we welho joteno davi.
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.
Uvah uu/lerafax/limisa_jayy.vumn anp uyj cbo zojmidoqc enyalzj er kko gub:
Wiosx cugidap5.nfuv dvas yde okjozj kemeppotf. xiasRammpi um lja sum-seqar hzayihtl yzas juklc xavipalyaw co omp vcu azakg em qzo evbev qudkej. Mnev qeutd ppe yara uz u jgziqd.
Upih dva tuadr-ep tpovNosewu() toqkey mo kusyopk xlu hcguxm yo a yof, rgaz uzig mnotXjat(), cxutz roy riqucujuz xaw toe, ge natu ip uzfvacle id ih IRAWuhizaNaotg.
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.
Eb dca fuxj gmaddiw, leo cuowg os rtir kii’ge qero di jum azp ciekj ozaan nehnitc fivu xgif jnu ugqiwbis.
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.