Dart fromJson example

Created At: 2022-04-15 13:15:01 Updated At: 2022-04-15 13:45:24

We will see how to use fromJson() a named constructor to convert json to class or model object.

Most of the time you will fromJson() after a network response from an http client. Http client would return us a json string or json which looks more like a map.

We will use api of the below to get data

https://jsonplaceholder.typicode.com/posts/1

Let's look at the network response

import 'dart:convert';
import 'package:http/http.dart' as http;
main()async{
  
  var res = await http.get(
  Uri.parse("https://jsonplaceholder.typicode.com/posts/1"));

}

It will return us json like below

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

To convert this json repsonse to an object, we will use fromJson() named constructor. 

First we need to define a class or model which will have a fromJson() constructor to convert the json response to an object.

class Task{
  late String title;
  late String body;
  Task(this.title, this.body);
  
  Task.fromJson(Map<String, dynamic>json){
    title=json["title"];
    body=json["body"];
  }
}

From this code, you can see that, we defined a named constructor called fromJson() and it takes a Map. This Map should be passed to as we call the constructor.

So we have the network response and the class with the named contstructor. Now it's time to convert the json to object.

To do it, in the main method, add this line

Task task=Task.fromJson(jsonDecode(res.body));

Now here, task is an object which is has been converted from json. See how we used jsonDecode to convert res.body to actual json and then pass to fromJson().

Complete code

import 'dart:convert';
import 'package:http/http.dart' as http;
main()async{
  
  var res = await http.get(
  Uri.parse("https://jsonplaceholder.typicode.com/posts/1"));
  Task task=Task.fromJson(jsonDecode(res.body));
  print(task.title);

}

class Task{
  late String title;
  late String body;
  Task(this.title, this.body);
  
  Task.fromJson(Map<String, dynamic>json){
    title=json["title"];
    body=json["body"];
  }
}



Comment

Add Reviews