DEV Community

Cover image for How to Convert JSON String to JSON Object In Flutter?
Pankaj Das
Pankaj Das

Posted on • Originally published at

How to Convert JSON String to JSON Object 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 go through how to convert JSON string to JSON object in Flutter?

How to convert json string to json object In Flutter?
You have to use json.decode. It takes in a JSON object and let you handle the nested key-value pairs. The code snippet will look like the below:

import 'dart:convert';
// actual data sent is {success: true, data:{token:'token'}}
final jsonResponse = await, body: reqBody);
// Notice how you have to call body from the response if you are using http to retrieve json
final body = json.decode(jsonResponse .body);
// This is how you get success value out of the actual json
if (body['success']) {
  //Token is nested inside data field so it goes one deeper.
  final String token = body['data']['token'];
  return {"success": true, "token": token};
Enter fullscreen mode Exit fullscreen mode

You can also convert JSON array to a list of Objects as following:

String jsonString = yourMethodThatReturnsJsonText();
Map<String,dynamic> d  = json.decode(jsonString.trim());
List<MyModel> list = List<MyModel>.from(d['jsonArrayName'].map((x) => MyModel.fromJson(x)));
And UserModle is something like this:

class UserModle{
  String name;
  int age;
  UserModle.fromJson(Map<String, dynamic> json) {
    name= json['name'];
    age= json['age'];
  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['name'] =;
    data['age'] = this.age;
    return data;
Enter fullscreen mode Exit fullscreen mode

You must need to use this sometimes:

Map<String, dynamic> toJson() {
  return {
    jsonEncode("phone"): jsonEncode(numberPhone),
    jsonEncode("country"): jsonEncode(country),
Enter fullscreen mode Exit fullscreen mode

This code give you a like string {“numberPhone”:”+225657869″, “country”:”CI”}. So it’s easy to decode it’s after like that

json.decode({"numberPhone":"+22565786589", "country":"CI"})`

Thank you for reading!!! We hope you liked the article!!!

In this article, we have learned how you can convert JSON strings to JSON objects in Flutter. Comment your questions if you feel any difficulties. Flutter Agency has a team of Flutter experts who will help you to solve your technical problems.

Discussion (0)