When and How to Encode and Decode Josn in Dart | Flutter

String and Map or Json are related to jsonEncode and jonsDecode. They are important when you want to convert string to json or from json to string.

Dart jsonEncode()

We use this function when we want to convert or parse a string from Json or Map. Let a look at an example.

import 'dart:convert';

main(){
  var map=
  {
    "name":"dbestech",
    "age":34
   };
  
 String mapString = jsonEncode(map);
  
 print(mapString);
}

Our variable map is Map. We send it to jsonEncode(map) and it parses or converts it to string object. And the printed result is

{"name":"dbestech","age":34}

 See the printed result has quotes which means it's a string.The braces are part of string as well. You can access each of the items in string using index. For example 

print(mapString[2]);

Would print

n

So the string becomes more like a List

jsonEncode is specially useful when you work with SharedPreferences in Flutter. When you store complex data structure in SharedPreferences, you have to convert it string using jsonEncode.

Dart jsonDecode()

We use jsonDecode we when want to convert or parse a string to Json or Map. Let's take a look at the previous example.

import 'dart:convert';

main(){
  var map=
  {
    "name":"dbestech",
    "age":34
   };
  
 String mapString = jsonEncode(map);
  
 var mapObject = jsonDecode(mapString);

 print(mapObject);
}

The above example returns us a string that's wrapped using curly braces. But it's still a string. When you want to convert a string like this is Json or Map you need to use jsonDecode.

So it will return a Map or Json 

{name: dbestech, age: 34}

See the above output doesn't have curly braces. It's a Map.  Because it returns a Map, so you can access the elements inside it using key.

print(mapObject['name']);

Would result in

dbestech

jsonDecode is useful in your flutter application when you retrieive a string from SharedPreferences and wanna convert it to Map or Json so that you can access the keys.

This method is also useful when you want to get class object or model object from string. So first you have to convert the string to Json or Map object and then pass the Json or Map to fromJson method. fromJson method will convert it to a related class or model object.

 AddressModel getUserAddress(){
    late AddressModel _addressModel;
    /*
      converting to map using jsonDecode
     */

    try{
      _addressModel = AddressModel.fromJson(jsonDecode(locationRepo.getUserAddress()));
    }catch(e){
      print(e);
    }
    return _addressModel;
  }

locationRepo.getUserAddress, returns a string which is pass to jsonDecode to convert to a Map or Json then which is passed to fromJson method.

jsonDecode is often used with fromJson for network response from an http client.

Recent posts