How to Convert Map/Array List to JSON String in Flutter

In this post, we are going to show you how to convert a Map, Simple Array List, or List of Objects to JSON string in Flutter and Dart. You may need to convert the array list or map to JSON string to save as a string or send to the server as a string on your app.

import 'dart:convert';

You need this library for JSON functions.

var ages = {"John":26, "Krishna": 34, "Rahul":67, "Maichel": 33};
String jsonstringmap = json.encode(ages);
print(jsonstringmap);
//output: {"John":26,"Krishna":34,"Rahul":67,"Maichel":33}

List<String> names = ["John", "Krisna", "Rahul", "Maichel"];
String jsonstring = json.encode(names);
print(jsonstring);
//output: ["John","Krisna","Rahul","Maichel"]

class Student{
   String rollno, name, age;
   List<int> marks;

   Student({
     required this.rollno,
     required this.name, 
     required this.age,
     required this.marks
   });
}
List<Student> students = [
    Student(name: "John", rollno: "12", age: "26", marks: [23, 45, 35]),
    Student(name: "Krishna", rollno: "12", age: "26", marks: [23, 45, 35]),
    Student(name: "Rahul", rollno: "12", age: "26", marks: [23, 45, 35])
];
     
var studentsmap = students.map((e){
    return {
            "name": e.name, 
            "rollno": e.rollno, 
            "age": e.age, 
            "marks": e.marks
        };
  }).toList(); //convert to map
String stringstudents = json.encode(studentsmap);
print(stringstudents);

The output of this code:

/*--- output ----
[{
  "name": "John",
  "rollno": "12",
  "age": "26",
  "marks": [23, 45, 35]
}, {
  "name": "Krishna",
  "rollno": "12",
  "age": "26",
  "marks": [23, 45, 35]
}, {
  "name": "Rahul",
  "rollno": "12",
  "age": "26",
  "marks": [23, 45, 35]
}]

*/ 

Alternatively,

class Student{
   String rollno, name, age;
   List<int> marks;

   Student({
     required this.rollno,
     required this.name, 
     required this.age,
     required this.marks
   });

   Map<String, dynamic> toMap() {
    return {
      'name': this.name,
      'rollno': this.rollno,
      'age': this.age,
      'marks': this.marks,
    };
  }

  static dynamic getListMap(List<dynamic> items) {
    if (items == null) {
      return null;
    }
    List<Map<String, dynamic>> list = [];
    items.forEach((element) {
      list.add(element.toMap());
    });
    return list;
  }
}
List<Student> students = [
    Student(name: "John", rollno: "12", age: "26", marks: [23, 45, 35]),
    Student(name: "Krishna", rollno: "12", age: "26", marks: [23, 45, 35]),
    Student(name: "Rahul", rollno: "12", age: "26", marks: [23, 45, 35])
];

var studentsmap1 = Student.getListMap(students);
//convert to map
String stringstudents1 = json.encode(studentsmap);
print(stringstudents1);

Same as output above.

In this way, you can covert Array List, Array List of Objects, Map to JSON string in Flutter and Dart

No any Comments on this Article


Please Wait...