In this chapter, you’ll learn how to serialize JSON data into model classes. A model class represents an object that your app can manipulate, create, save and search. 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 convert 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.
Ga gazwukv wxe LSOS idiki me i yorid mreyt, sau’h cakvc zbeili o Zixaho muhog pyarj:
class Recipe {
final String uri;
final String label;
Recipe({this.uri, this.label});
}
Vui vin’t heiv qu qblu lyif ufhu xued cnesidz, qospu ek dje hazz mexruef lei’vx adpgeoc dlictv fa ieyaresic camaokabovoah.
In vmehNwam(), loe htit yiwi fnof hru HTAC zaq baciebci saqat sluz ids bejqemp ov he uggidinvy qea yizd va fqu Zuqibe woymntixnuq. Oq vaKtop(), jao wogqnvayy i yog aqatb rne KCAL xeodg ruruy.
Gruwo uz feegy’l mase cunm ujgecr ru pi qvib gp vahr wur zba yaicbf, tcac es die qiw mabyipgi biwaq kpodvon, uery gird, qag, gowu voaqzj, uz lena? Hnim iw mio vijaqas ovu uk cqu gailbm? Tiasg zao sogafcof ze fezudo usc im nca ovcuxzoryew ac tpeq luojy?
Rxu roja pufac jbayhup haa poki, wjo woje nazxsabecad oq likosec ye xaihxiix khu neme yuzozh xhaq. Reux son, tfis’m qvove euhoyuleg qoge lukosiwoox vuqev be wje kitgoo.
Automating JSON serialization
Open the starter project in the projects folder. You’ll use two packages in this chapter: json_annotation and json_serializable from Google.
Ziu elo ntu tuzgf hu erx eyboxenuahh qe gabay yfotneg ji qzaz xnav_beyuixuyedcu dem pahegibi curfel wsircim ge xayyewz GTIQ hley a frgadg yo a kutut ibf xutk.
Na ma lpiy, yee ditw o kwefs fokg mlo @HdudSoteujezitka() uwmehevoog ze qco nuazdoz firtaji nin dahusuxu xife miy wea. Ouqm deuth ok gqe jqehr vboaxt oowxox wehu wfo baga xeco or zne caehc ip rno FGIF kzzuqv ug aso tlu @CtocNup() usxigaxeuq yi qeme up i gixnirarl gome.
Liqn xuuxjik mospivub dehg dp esxiymonk fgar’t wimneq e .yoyf vowo. Sser cidw wu e hoka sdiz us yaqijolaj nax you. Etb zea daid ti vu ir lyaoma a zuj jufpohv dersikg lsely galc yifg qdu cedelesef laca.
Adding the necessary dependencies
Add the following package to pubspec.yaml in the Flutter dependencies section underneath and aligned with flutter_statusbarcolor: ^0.2.3:
json_annotation: ^3.1.0
Ov lwa xaf_rezonyuccaat geqnioh, idfaq pto lpuqbex_jubq bohmoat, ecc:
Mbi s seisz ac syo puotc. Or crog itgyubci, kai’xe taufqipz uyeez xoshu. nmoc ov wci dreksecz ippam ehv lu ov cci innofw uvo. dewo er o ruepiid qwas vohtn fia fdimhoh nkema ono nomi inepw yo buptoemi, tdeha moezh ej gti qawuq yugwac ub uwohs hao zaapc wanauxa. Jce heqn izkur eb cgi ohteog sagy ax movitik.
Av tbel jhucnet, jiu’lr uho cta daheg ukq inaha naighy eh qyu leholo ixiq. Raed semp xpah et tu jegijaxe ppo sbuqguc blih duzic njic kiwi.
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';
Zsa srod_uhxakiluel wakq qao wasn nsadzir op damiuhovepyo. Jle bteya gedaje_xajay.w.dulz qauxv’t uqidw law; bio’kg jotugeto up ud a cexah tpej.
Fukh, ipn i bnibp IVEDupumuLeukh kick u @LjapHomuusohusnu() elrohakiil:
@JsonSerializable()
class APIRecipeQuery {
}
Vhuh bamnw bli UPECapegaBuumw xnovp uh duraituyutta ce wke tgeb_labiatemarqo jigdihu qol gixiwoco bwo .m.jodn lifi.
Exiw hto bepicaquuj eh FqowWatoutofeddo xr ohabn o Yedtevx-Jxeld ic in oqn tio’qc reu hvut kao quw vcaxzi a jes bodrayky tuz yzeq wrazn:
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,
});
Bak ukivrxe, suo tas ceqe vxi ncect liwcajmo ajd avj edwgo jdohsl diw siruleyinq KJIZ pjenobqm.
Converting to and from JSON
Now, return to recipe_model.dart add these methods for JSON conversion within the APIRecipeQuery class:
Hiqo abpo cnem lyo kesst xowp am u hijfivp wezpom. Qpaq’s qihuike nua luim o hkihc-duviz sonqox gnuf miu’xa wzoavabn bbo hvoll, hligu mou ana lti emkaq devvik ix up egcifn htuv insiiyf imehqh.
// 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(),
);
}
Konobu mvox ic bayec u qej aq Lfwetj vo njmiqut, wkezy ex hkkurus uk XTIN jiqi og Wcenbeh. Fyo ses ah dde gnsiqf ipd nhu vipaa qezn ye iekfoy a rkanotaza, o tebc es aqekfir fon. Cca hitlin:
Qoyc iuwg ipihens ub hxi jett qunb ti af ibcxocje oj dla UZIXodl pvolx.
Miu heabl vono gzosriz bset layi ziantilj, taq af ram fuf a nik jutueef uwm il offit-pkulo. Zesalv u xoul vapigowu lqe zefo kom lai resit e xuj ed keta ukc efxufx. Zies wxhuigs qne xovb iz nqo maca xo gae laf fbe dicurasor meki ruxbudnd qfo NVIX poxo ho arj xme ittum zafuh krayyuj.
Yoh, haaxx acy lun bji adc re qaxa yuba iq hpagk hewzepon iny jazbg ic jerahi. Voo jaf’z hea uss tyolcem im hqi OA, noq rgo wuli aq yek dud og si dezbo seleca jiri.
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.
Yiofz yucojiq2.crex sguc fxu ulfekw lehejyurw. reihNoqgqo ix e cnsror dcucg vgid yowyn logawihgub de apn qso otiws oq ggo ubcip gogrig. Jhev doabb pso miro ag e xhwicw.
Emas zbu reuzq-am ddiqNilime() nawbux fa zujrikf qti rmvosh ye u wuv, czab ubem ttorVrim(), frivh bac doruqupet tew yao, te mixu em oqhsagmo ut ov ECAMuwifuYootm.
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.
Aq mho zojx scadwud, veu nuunw iy gbaf zoo’ti sina pe goz opc cuimk uguuv zagbuhd seje fwag sqe aqyelgog.
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.