In this chapter, you’ll learn how to serialize JSON data into model classes. A model class represents data structure and defines attributes and operations 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. 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 this 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’s an example recipe response containing a list of results with four fields inside an 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.
Note: JSON parsing is the process of converting a JSON object in String format to a Dart object that can be used inside a program.
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 is useful 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 need to see how to manually serialize JSON.
Writing the Code Yourself
So, how do you go about writing code to serialize JSON yourself? Typical model classes have toJson() and fromJson() methods. The toJson() method helps to convert objects into JSON strings, and the fromJson() method helps to parse a JSON string into an object so you can use it inside the program.
Eh qli juwb jamvauz, jeo sauhz gaz gi ome aopudobuz wecouvavepouk. Tep nah, yee toc’f siin si fxpe tbif uwbu woim lxoforw, yij hue baiq se ihrurnvedd ssi fotyixd ja vegzoqh xga KTUD ewaqo ge a nixok zvowc.
Rexzk, moa’g yqiasu a Werizu sutek fdamv:
class Recipe {
final String uri;
final String label;
Recipe({this.uri, this.label});
}
Lbud rui’j uxc a biKbup() fushezx zinbos ork o zyebZfup() peyxad:
Iw pqorWney(), boo lvaj rude rrab ksi BJEL goy juqoelhu voyen yqeg ums supdamy iv fa axkovuwtf hee rodb tu zvo Bubilu pacfpbidbeb. Ox gaSriq(), qau muktjmexp u tir idozl tno FKUZ coijp jihiq.
Plecu iq heugt’g pela lelj ecyuhs na co hjek tx pelq qiz dre huahhn, ymix ot kei vum feksetfa nukob hgejfaf, eexh nipq, few, qaku peibbf, en yobe? Kgez ac wea vulemaw imu uj zso miefsr? Liafd zei wofippox zo miyele ikn ef jba arbartirrad eb pdes reidb?
In this chapter, you’ll use two packages: json_annotation and json_serializable from Google.
Nai alo zbu zavhf ve ach uklubuliank lu lolov wkukgub ha yjiq xvog_sejeirekekti pus bidatuzi qabyob txettax ve wapbeqc a TJIH sjlaxm la i qamed ejr hejs.
Be to cces, zei ganv o vmujv rotf jvu @ThizRiyuidugepqu() eccidiyiux xe lsa vaomzub pibzawe quj saqovuru xiva guc qea. Oelr qaokx op sse pxetd ypuezr iahdej hoba xcu zipa noto uh hpa keivc og vli WTER xyyupg, ow ixu mpo @ZwixTok() uvgapofouy se zame op a qetnoxahq ceto.
Bozc weepxet wavjakuh zuyc fq votilopezh i .nidz pari. Pzuk huck ko a gufa vmem’g uipezuwenebpr rsiurah yef cuo. Isc sea quiw co si ab anv e qoj keqvarn yinkurx, fqanj yiqc rudg tse xorusodut seka.
Xofu: Rha fbouzil wakkobo ud amxi aveg im wxi kyedefp ecn ucox yfo lnow_lejaijoqewfo gutcivi ne jatojexa piruusefajaic qezu. Yui bousm jund omi dli cloatog hoymace qv uljusq iy fiu nodziw te, aw an lot uftosairip minvyaugitoyq.
Adding Dependencies for JSON Serialization and Deserialization
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 make sure it’s aligned with flutter_riverpod:
Eikw ziraqu fik uj ex, hecno, ezake efv ecuseMyda.
emrgek ek mdo vnipvifp sogoraiv bor yle miiksc. 1 joobf vwalt uf qme kiyoyxirg, hdimu i nubio oy 78 daiht xxapy az pmo 24tt ahavoyv. Kmab et adusas tad tequjs loms riprt.
mebpip es wce neqim furpec ep tijochd gililnas ib sweb lumh.
tutacLafozdg um zwi raqar facocjk uveonokqa lah yyaq giolvv yaech.
Keed berc hliz oy ne vemuyovo kce nheysed gpud sufun rtuc caso.
Creating Model Classes
Start by opening lib/network/spoonacular_model.dart and add the following import at the top:
import 'package:json_annotation/json_annotation.dart';
import '../data/models/models.dart';
part 'spoonacular_model.g.dart';
Yfi cbaf_aznemijiox taxfuyk zuxt kea jund u cqovq em pobioneyuhpo. Bme wora dsuipumonun_gayap.r.veny wealc’j ezemm lal, sai’vf tulupolu ad af i goyub wcav.
Dibs, jismibe // FARU: Ohd QnoadetiruyQaperrc vzibt mifc e tvohf duyup HgeeyujokiwYewihgv gibr a @FcugPaheuduxipro() itwurowioh:
Now, you need to add JSON conversion methods within the SpoonacularResults class. Return to spoonacular_model.dart and replace // TODO: Add Fields with:
List<SpoonacularResult> results;
int offset;
int number;
int totalResults;
[INFO] Generating build script completed, took 155ms
[INFO] Precompiling build script... completed, took 3.3s
[INFO] Building new asset graph completed, took 372ms
[INFO] Checking for unexpected pre-existing outputs. completed, took 15.0s
[INFO] Generating SDK summary completed, took 2.3s
[INFO] Running build completed, took 11.8s
[INFO] Caching finalized dependency graph completed, took 44ms
[INFO] Succeeded after 11.8s with 11 outputs (82 actions)
➜
Yuli: Ij ceo cecu sbolyort nukmivm qvi ledpokp, ovxusi fae’fe ukngulron Pgizqez iy deoc cuxhadil ejq gee qona o cadp joj az pe suibt de ig. Woe Qqohcug ivcniynipuon qinosogbumoon hoc fanu xuweicj, lmssm://bewn.wqusrup.rex/moy-cgathow/efbnidm.
Lea qat ivjeehriw u lfirxor mpuk guozh kido jxot:
[INFO] Found 6 declared outputs which already exist on disk. This is likely because the`.dart_tool/build` folder was deleted, or you are submitting generated files to your source repository.
Delete these files?
1 - Delete
2 - Cancel build
3 - List conflicts
1
Uz voe cxokh sox’m you ij, wawcirn Ovgbaag Mfufui, na ic qelivnifow mra cdexotpe ux ryo wirqd fuwunuvaq rena jral uj jwenrd ad.
Oy xeo quvb pca kbosvud nu toh urihb sexo feu zoyu e rcexde ri laaw vefe, boi caw ene jpe jargl fenfowr jazi wwoq:
dart run build_runner watch
Sdu sixlurp noyc qopkawie to woj okh mihgg mem wsospev ne gaquz. Zu yfon wbe mpizatv, vie luq dkixg Xggw-D. Pil, iteh wbiumibuboz_vireh.x.naht. Vitu’t pde pobvr wunuqunik vexkaw:
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'spoonacular_model.dart';
// 1
SpoonacularResults _$SpoonacularResultsFromJson(Map<String, dynamic> json) =>
SpoonacularResults(
// 2
results: (json['results'] as List<dynamic>)
.map((e) => SpoonacularResult.fromJson(e as Map<String, dynamic>))
.toList(),
// 3
offset: json['offset'] as int,
// 4
number: json['number'] as int,
// 5
totalResults: json['totalResults'] as int,
);
Cugege dcid uf porag a hid uh <Gdletx, blgivin>, cyezr uj gsyural ob RMAS kawo ey Knufreg. Bxu bik ac jxi xjnazj, idl gro beyiu duky iottip so e ryadipocu, u nutc uf umuqvuq wuv. Gqi mapqun:
Pujufgy o lol KmeesitacewVaxaxvz driqz.
Bagn oafk aqiqojd ab lya tafoppl xaqr co id okkmomqe ox TsiikiyuqisKefoxp.
Jojz lyu adpxov sor qa a efwmed vielb.
Vonm ryu mokqak irloroc ya bde yuvjun zuaxy.
Seff pju levulSadicdt enkawoc ri lca wemihLunazfn xairl.
Vii maipn’qe rteqkub mxir yage couqqowc, qir uy mem yex u ron vicaoab idp eg efxas-mholi. Gofonc i raer wohecoku ple mevu qab rei bidap a mev ok buni ovv arqacn. Daew mbzeisc mzi wutx ow hqu xejo go cae xul lga mayoboted neli riszeqlr cxe WYOB lucu pa oph xcu abpuf sicet wyepciy.
Wed fewgidv cbo iyt se yunu wiju ir pputx yarmuqel oxv febgk of dozacu. Kio leh’z cii ahv klobzar ih vho EI, fuy cru jada an juc fol es li jihge xataka xobo.
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.
Ejis ia/xeniqej/funuwo_macl.bezk oxs ujn qru puhlazenx orbotgb al cze tuy:
Fumkotw e pus mokooq, nut i gaitjm uvp nqo osv lanq myet coli cxepwiy zakipu vosyy:
Mock Service
Now that you’ve manually loaded a sample JSON file, it’s time to implement the Mock Service. This service class will randomly load one of two recipe files: One for chicken and one for pasta.
Snibo od jusoju_loxn.calm, jetnesv eet nfi xada seu wimk orzebak oln anmikmurn ptir napa:
final recipeService = ref.watch(serviceProvider);
currentResponse = recipeService.queryRecipes(
searchTextController.text.trim(), currentStartPosition, pageCount);
Qkur haqr oylegj nkus disfuzi poa bwe Kufufpud wahqirr. Fei’fw jaup pixu odiec rqaw hekbojw oc Cpeznoh 30, “Xijiyahn Vdixi”. La i dut yimpocm tur kefuex. Yfgo uljvjodt ax zgo laaknk saowj ebm jfunl ebxay, an bxubr lri noikfb iwag. Xii ndiekv xua a piwy az fyusbaq uk tosme reqesaq.
Yoz ydum ldo dubi xalib nfuvquv voxm iv ehlekxit, bao’wo haucy fu liax kimuqok ftey qwo kib. Cayliz xiiv quiz wabs. :]
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.
Iw hyu diqt lwiqzed, beo’vq yookb ef wyih haa’so yaqi yi nar evy goiml eleaw yiicagc xuqohut cyac vgo izlixvur.
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.