Conversation

Your input fuels progress! Share your tips or experiences on prioritizing mental wellness at work. Let's inspire change together!

Join the discussion and share your insights now!

Comments 0

Sharpen your coding skills—try JavaScript challenges on TOOLX now!

advertisement

Beginner's Guide to Working with JSON in Dart

JSON in Dart


1. Parsing JSON in Dart

JavaScript Object Notation (JSON) is a lightweight, text-based open standard, designed and developed for human-readable data interchange Douglas Crockford specified the JSON format, which is also described in RFC 4627. Application/JSON is the official internet media type for JSON and .json is the extension for the JSON filename.

JSON, being derived from JavaScript is a language-independent data format. It is included in many modern programming languages such as Dart, to generate and parse JSON format data.

JSON parsing is commonly used in applications to fetch data from the internet.

Depending on how much JSON data must be processed, there are two options:

  • Write all the JSON parsing codes manually
  • Automate the process of code generation



Write all the JSON parsing codes manually

Parsing the JSON code manually requires the following processes:


  • Encoding and decoding JSON
  • Define a type-safe model class
  • Data validation
  • Serializing back to JSON
  • Parsing JSON to Dart code using a factory constructor

A JSON parsing code written manually can consume more time and can be error-prone if there are lots of model classes.


In such a case, code generation tools can be used as follows:


  • Json_serializing
  • Freezed



Understanding the structure of a JSON document.


{
"CarName": "Camry",
"Brand": "Toyota",
"Reviews": [
}
"Rating": 4.0,
"Condition": "Excellent"
}
]
}

In this code, a JSON object can be seen with the keys CarName, Brand, and Reviews as a list inside a JSON document. Inside the Reviews list, there are two keys namely Rating and Condition.

A JSON document represents a map of key-value pairs.

JSON data can contain both maps of key-value pairs using ({}) and lists using ([]) separated by a colon (:). Each key-value pair is separated by a comma (,). Nested collections are created with a combination of these two, which represent a complex structure in JSON.

A key-value pair consists of a key-value, separated by a colon (:). The key is a string, which identifies key-value pairs. The value can be any of the data types.


Lists the different data types included in JSON.


  1. String: Surrounded by quotation marks ("")
  2. Number: Integer or any numerical data type
  3. Float: Double (decimal number).
  4. Array: JSON array
  5. Object: JSON object (can be nested).
  6. Boolean: True or false
  7. Empty: Null



2. Encoding and decoding of JSON in Dart

Sending a JSON response over the network. The entire payload is encoded as a string.


The JSON is encoded as a string.


final json = '{ "CarName": "Camry", "Brand": "Toyota", "Reviews": [{ "Rating": 4.0, "Condition": "Excellent"}]}';

The encoded JSON must be decoded to use it in the user's applications.


JSON data must be encoded or serialized before sending it over the network. This process of manipulating data structures into a string is called encoding.


When JSON data is received as a string from the network, it must be decoded or deserialized. This process of deserializing the data is called decoding.



Decoding JSON with dart:convert


import 'dart:convert';
main(){
final json = '{"CarName": 'corolla', "brand": "Toyota"}';
final parsedjson = jsonDecode (json);
print('${parsedjson.runtimeType} : $parsedjson');
}

In this code, a package dart:convert is used to decode JSON data. Variable JSON represents response data received from the network. The JSON string will be decoded to JSON using the jsonDecode() function in the dart:convert package. Lastly, the output of the parsed JSON will be printed.



Parsing JSON to model class

Dart is a statically typed language. Hence, it is essential to convert JSON data into model classes. These model classes represent real-world objects and make the most of the type system. The values in the JSON data should be studied and a Dart class with all the values in the JSON object should be created.


//Car_data.json
{
 "CarName": "Camry",
 "brand": "Toyota"
}

In this code, there are two keys, CarName and brand, both of type String. So, a new name rating class can be created in Dart to represent this data, and these variables can be added. After that, factory methods must be used to map the JSON data to the Dart model object.



//main.dart
class Cars{
Cars({this.CarName, this.brand});
final String CarName;
final String brand;
}

In this code, a model class Cars has been created which can be used to decode JSON data.



Cars.CarName
Cars.brand

This code displays a fragment of code demonstrating how JSON data can be read using the model class instead of parsedJson['CarName'] and parsedJson['brand'].



Factory constructor

JSON parsing is done using a factory constructor and allows users to create variables and perform validations before the result is returned.


A factory constructor is used when there is an instance of a class in memory which prevents the creation of a new instance each time the class is used.


In other words, a factory constructor will return an already created object, thus improving memory and performance, whereas a constructor will create a new instance each time.


factory Cars.fromJson(Map<String, dynamic> data){
final CarName = data['CarName'] as String;
final brand = data['brand'] as String;
return Cars(CarName: CarName, brand: brand);
}

In this code, a factory constructor has been created for the Cars class. The variables CarName and brand are assigned to the JSON data CarName and brand respectively.



import 'dart:convert';
class Cars{
Cars({this.CarName, this.brand});
final String CarName;
final String brand;
factory Cars.fromJson(Map<String, dynamic> data){
 final CarName = data['CarName'] as String;
 final brand = data['brand'] as String;
 return Cars(CarName: CarName, brand: brand);
 }

}
main(){
final json = '{"CarName": "Camry", "brand": "Toyota"}';
final parsedJson = JsonDecode(json);
final Cars = Cars.fromJson(parsedJson);
print(Cars.CarName);
print(Cars.brand);
}

In this code, we include a class Cars and a Factory constructor has been created for the Cars class. In the main() function, JSON data is being parsed using the Factory constructor and then, the values have been printed for CarName and brand.


Note: If you are using a 2.x version of Dart, you may get a type safety error. To resolve this, you can add a? with the variable declaration to prevent a compiler error as follows:

final String? CarName;
final String? brand;



Serialization with toJson()

Parsing JSON data is very useful, but at times depending on the scenario, a model object has to be converted back to JSON data for sending it over the network. To accomplish this, use the toJson() function in Dart.


import 'dart:convert';
class Cars{
Cars({this.CarName, this.brand});
final String CarName;
final String brand;
Map<String, dynamic> toJson(){
 return{
 'CarName': CarName,
 'brand': brand,
  };
 }
}
main(){
final json = '{"CarName": "Camry", "brand": "Toyota"}';
final jsonMap = Cars.toJson();
final encodedJson = jsonEncode(jsonMap);
print(encodedJson);
}

In this code, we include the class Cars and a toJson() method defined for Cars. The toJson() method returns a map literal with non-null key-value pairs. In the main() function, the Cars class object is created with the values for CarName and brand. This object is then converted to a map using the toJson() method and stored in a variable called jsonMap. This jsonMap is then encoded and JSON is then printed in the console.


Dart Dart Programming JSON in Dart Parsing JSON in Dart JSON Document JSON Structure Encoding JSON in Dart Decoding JSON in Dart JSON model class Factory constructor in Dart Serialization with toJson() Factory Constructor

advertisement