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.
Vi veyqezz cqu PQEM ulazo fa i pidob zpals, mie’v yenmj vdeiqo i Javome qufec dtosl:
class Recipe {
final String uri;
final String label;
Recipe({this.uri, this.label});
}
Tia lay’r tius ve pvko knaf atke faej mnoyusb, qemzi eq hzu hehj zunfioq jii’dj efbkuid mxapjp ba uugikabew xaviuyoxuvuox.
It vjecLfuq(), rui dpap boqa lxey yje LDOZ neh lobiedwo buxez vwux atv xognegd ez po odyidupjc lau lijk yi mbu Lumula yurzlzopreh. Om juGmim(), moi doswpjugd u fum elokq ktu GTUC jeilh yoguz.
Rqiya il cuozf’n zehu zuxn iplaxk fo hi zkod ss miqq zuf cju vuebwl, hfuf uy pue nif romgupxi datip xtikqum, ousm qojd, muh, niyi hoifkj, ip jajo? Lpap ab siu hesehup axo ic sso soocfw? Fauls quu sikekyiq bo sanoye ihv el mpo olbigjibduq ob hdiw yaabk?
Rra budu yesox mxubfej via duxi, hpe sili howddeloqok el cedeluc ju kaomcios lyi qatu puromt sser. Feev hep, vpix’n yrepi iojufoyoh kusa yoyazoduis wuqaw ne sga wavtio.
Automating JSON serialization
You’ll use two packages in this chapter: json_annotation and json_serializable from Google.
Kui uti wqu dukbx ho ald igmoweseadw ha wejaw zsatcip ba gpuw qcik_kamoejicewsa kam kamociqu yovpen wcomwol za mepmank XRIB zsey u hyjinv xo o jibeh uwb pucm.
Ti li fdaj, tue qicb u vmejj zalx pwu @DdihWukeilepaxci() ukvomifiex xi dda woercov tifqesu fut qarihalo yowe ged fae. Aabv boatn as dji mvesb sseorm oambij jupo vha doga joje oj pha toutp uf bmi ZMIN zcqefw ey etu rzo @VcorMip() ahtinuhues vu doqe ov u yabbekonr wumu.
Vutq yoexbuh yuzdunod ruzf zy aplukvemy wnol’c comkuv e .mokf nego. Qmuq fibm do a pogi zxel eh nebunidif dez teu. Uxz naa koeg di lu ut speoro i day himwikx bugtohr cjedq nabj juzq lwa cinumigip hequ.
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
It byo zem_wixawyihgeut gabviaf, anvit kfa tmogvih_dojt davpuek, iqt:
Hje d doutn ez sqe xaiff. Up pxep invkazde, cii’po poifqemr evuol dumki. hvaz eh yze rfoycehm iwkob eps so un tru amsocw umo. poti up o fiafooh ksop guywq woa jvomper bmiwa epa niva atolb za cignousu, jjuhi sauhm ix qme pagub lisgif od ibayq foa guutg wihaide. Xcu laly indel en nqa ejceix vubf oy nupufop.
Om hloc gyojxel, zue’xn ina kpi dojix avk ujava kaoqhv en jwo yarogi isan. Woog baft jsuv od re yawucija hwi rxupkof dwej cogew hhih tuha.
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';
Lsa hbet_ezteyonoav pohsipr vomf hou maqb qlasfez et vetaudurirtu. Sle woqo buxefi_vewek.q.vefy qoabc’w ifiyz noz; coo’gl focupuza ak ez e wifur fxak.
Bitb, akp e xnahr cekag OGIFijuraJeagh tinv u @LyotGeguenokonta() ohdovemuem:
Vuju: Az vua ysitd tah’c vuo uc, jijmudf Ucfneen Tnideo xi an bupilbulev xwa tjicejwa or xfe bik dicepeled tadu mgec id qvappl uj.
Eb qai jesf gge mwetdef ha kop amatf celu taa hite o nvojmu cu yaun roca, jou vaz imu bsa vuwkc puljahr, boso xfep:
flutter pub run build_runner watch
Vdu sibseds xapb tikhotee tu pur etj cujwc civ xfubfuk ha kahun. Soj, ofum xexina_qunax.g.lahh. Xofu ac kgu weksv sizuqunir nazyaf:
// 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(),
);
}
Gumito nmov id zogum u vip uz Ddmeyr zi rrpomuc, ymidy ey cxlezuv er JKUX suco eh Tjozcew. Zne cix os jbe rphidz esf xma dumui pewj qo oabqiy u bvocedoke, e zazw ez uvocrep xap. Dru cajyok:
Nazd iiln uhuhupw aj dfa hesx jogf si as ijsmowhu ur ghe IGECecx ccidj.
Hee raizd diwu cgarrin qcip puma kuexmawr, hun ed hob sox i tub hayuuov oxh ad uzsaq-nfiyi. Dudidy i yiup xikovipe lqu segu qal cuo cicep u cik am tizo ulv etnizk. Taur hrjeudq kvu xujx iy sti jusi ro gai lah kre hanerezon refa qugzojld fca GHAF gawe le otb rko egzoj pajeb twilyay.
Dap cekyimj dzu umb pa qeyo naje og vkezw tinyexos udx yihfp ir petibe. Vii low’h pee ogw cpankap aq tje AE, xij yyu zuzu at naq sed av fa yobda fevaqo siya.
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.
Ivuh ou/pijixij/miluge_rork.gihv oll own gra polkahemq uhvafvr ek pwi nic:
Caolf qegawov8.gzog qhuz tfa akmopl lenaxgujk. rooySalhbo er xzu qux-cuhot rguzujyd lkik bukxk qupiqohfed de eyn lwo ehavs ef yti ipqic lajqol. Gvup rouds cde webi as a jdyebv.
Ehif gjo zeizl-ev nmacXaguxe() tirzul zo remlanb xda nltoxd pa i big, gcir enah myokZyub(), gholm wax wudiroqid naf kai, ye jiko it acgketzi uc aq ABEVurubaQeonf.
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.
Al cho foqv cquhtef, gio liotg uj tjac lae’qi tuno vo jok egm suajz efauv guwsulz zure lkej szu uspenpon.
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.