Saturday, July 14, 2018

Dart: Json Parsing

Welcome to this post.

In this post, I am going to cover about JSON parsing in Dart.

What I will do on this project?
 1.  Get data from Rest API.
 2.  Parse the JSON Data

Let's Start-

First, take look at the data source. I will get the data from this link.
https://swapi.co/api/starships/

JSON sample.
This response you will find that link
{
    "count": 37, 
    "next": "https://swapi.co/api/starships/?page=2", 
    "previous": null, 
    "results": [
        {
            "name": "Executor", 
            "model": "Executor-class star dreadnought", 
            "manufacturer": "Kuat Drive Yards, Fondor Shipyards", 
            "cost_in_credits": "1143350000", 
            "length": "19000", 
            "max_atmosphering_speed": "n/a", 
            "crew": "279144", 
            "passengers": "38000", 
            "cargo_capacity": "250000000", 
            "consumables": "6 years", 
            "hyperdrive_rating": "2.0", 
            "MGLT": "40", 
            "starship_class": "Star dreadnought", 
            "pilots": [], 
            "films": [
                "https://swapi.co/api/films/2/", 
                "https://swapi.co/api/films/3/"
            ], 
            "created": "2014-12-15T12:31:42.547000Z", 
            "edited": "2017-04-19T10:56:06.685592Z", 
            "url": "https://swapi.co/api/starships/15/"
        },
      ...
    ]
}

This is the json Sample. I just take only results data. It's a collection of the result. SO create the model class first.

Model Class

We have so many things on the JSON result.
so you have to create all the field.
Note: If you don't need some field, simply skip those.
  final String name;
  final String model;
  final String manufacturer;
  final String cost_in_credits;
  final String length;
  final String max_atmosphering_speed;
  final String crew;
  final String passengers;
  final String cargo_capacity;
  final String consumables;
  final String hyperdrive_rating;
  final String MGLT;
  final String starship_class;
  final List films;
  final List pilots;
  final String created;
  final String edited;
  final String url;
Note: here films and pilots are Lists, not String.

Now create the constructor-
RestModel(
      {this.name,
      this.model,
      this.manufacturer,
      this.cost_in_credits,
      this.length,
      this.max_atmosphering_speed,
      this.crew,
      this.passengers,
      this.cargo_capacity,
      this.consumables,
      this.hyperdrive_rating,
      this.MGLT,
      this.starship_class,
      this.films,
      this.pilots,
      this.created,
      this.edited,
      this.url});

Now create a factory method-
take a map and return a new RestModel.
factory RestModel.fromJson(Map<String, dynamic> json) {
      return new RestModel(
          name: json["name"] as String,
          model: json["model"] as String,
          manufacturer: json["manufacturer"] as String,
          cost_in_credits: json["cost_in_credits"] as String,
          max_atmosphering_speed: json["max_atmosphering_speed"] as String,
          crew: json["crew"] as String,
          passengers: json["passengers"] as String,
          cargo_capacity: json["cargo_capacity"] as String,
          consumables: json["consumables"] as String,
          hyperdrive_rating: json["hyperdrive_rating"] as String,
          MGLT: json["MGLT"] as String,
          starship_class: json["starship_class"] as String,
          films: json["films"] as List,
          pilots: json["pilots"] as List,
          created: json["created"] as String,
          edited: json["edited"] as String,
          url: json["url"] as String,
      );
  }

See the full class code of RestModel in Github.

Parse JSON

Now time for getting data from the internet-
Create the main function
void main() async{
}

Save the link in a String.
final link = "https://swapi.co/api/starships/";

Create a new list. And the subtype of this list will be RestModel
List<RestModel> list = new List();

import HTTP package and make a request
var res = await http.get(Uri.encodeFull(link), headers: {"Accept": "application/json"});

next steps-
1. if the response code is 200 then the response is successful
2. decode the response code with the help of json class that include in the package 'dart:convert'
3. after decode it return a map.
4. take only 'result' from the map and save in a new variable.
5. loop this list and for every entry and return a new RestModel

See the code-

if (res.statusCode == 200) {
    var data = json.decode(res.body);
    var rest = data["results"] as List;
    for (var json in rest) {
	var model = new RestModel.fromJson(json);
	list.add(model);
	}
}

print the list
print("List Size: ${list.length}");

Output:
List Size: 10

Full code-

import 'package:http/http.dart' as http;
import 'dart:convert';
import 'RestModel.dart';


void main() async{

	final link = "https://swapi.co/api/starships/";

	List<RestModel> list = new List();

	var res = await http
			.get(Uri.encodeFull(link), headers: {"Accept": "application/json"});

	if (res.statusCode == 200) {
		var data = json.decode(res.body);
		var rest = data["results"] as List;
		for (var json in rest) {
			var model = new RestModel.fromJson(json);
			list.add(model);
		}
		print("List Size: ${list.length}");
	}
}

That's it.
If you have any quires then use the comment section. Feel free to put comments.
you can easily parse json.
Happy Coding.