Book Image

DART Cookbook

By : Ivo Balbaert
Book Image

DART Cookbook

By: Ivo Balbaert

Overview of this book

Table of Contents (18 chapters)
Dart Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Making toJSON and fromJSON methods in your class


JavaScript Object Notation (JSON) is probably the most widely used data format in web applications, so it is a common requirement for a class to be able to serialize its objects to JSON strings, or reconstruct objects from JSON strings.

Getting ready

JSON is lightweight (not as verbose as XML) and text-based, so it is easily readable by humans. It starts from the notion that the state (or content) of an object is in fact like a map; the keys are the field names, and their values are the concrete data stored in the fields. For example, (see project json/job.dart), say we have a class Job defined, as shown in the following code:

class Job {
  String type;
  int salary;
  String company;
  Job(this.type, this.salary, this.company);
}

Next, we construct a job object with the following code:

var job = new Job("Software Developer", 7500, "Julia Computing  LLC") ;

Then, it can be represented as the following JSON string:

 '{
     "type": "Software Developer...