How to Decode JSON In Flutter ?

· 3 min read
How to Decode JSON In Flutter
How to Decode JSON In Flutter

JSON is short for JavaScript Object Notation and is a way to store information in an organized, easy-to-access manner. Generally, the entire communication between the app and the server is through JSON. So in this article, We will learn about How to Decode JSON In Flutter?

What is JSON?

JSON is often used when data is sent from a server to a web page.  JSON is a lightweight format for storing and transporting data.

How to Decode JSON In Flutter?

To Decode JSON follow the steps below:

json.decode()

or

jsonDecode()

In Dart 2 all screaming-case constants were changed to lower-camel-case.

Ensure to

import 'dart:convert';

Inline example

String rawJson = '{"name":"Mary","age":30}';

Map<String, dynamic> map = jsonDecode(rawJson); // import 'dart:convert';

String name = map['name'];
int age = map['age'];

Person person = Person(name, age);

Note: When I was doing this in VS Code for server-side Dart I had to specify the type:

Map<String, dynamic> map = jsonDecode(rawJson) as Map<String, dynamic>;

Model class example

The model class includes map conversion logic:

class Person {
  String name;
  int age;
  Person(this.name, this.age);

  // named constructor
  Person.fromJson(Map<String, dynamic> json)
      : name = json['name'],
        age = json['age'];

  // method
  Map<String, dynamic> toJson() {
    return {
      'name': name,
      'age': age,
    };
  }
 
}

And the JSON conversion is done like this:

String rawJson = '{"name":"Mary","age":30}';
Map<String, dynamic> map = jsonDecode(rawJson);
Person person = Person.fromJson(map);

Simply user need to import like a below

import 'dart:convert';
Decode : JsonDecoder().convert("$response");
Encode : JsonEncoder().convert(object)

Conclusion:

In this article, we have been through How to Decode JSON In Flutter?

Keep Learning !!! Keep Fluttering !!!

Still, Need a Support for Flutter Development?

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

FlutterAgency.com is one of the most popular online portal dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge on Flutter.

Leave a Reply