How to Convert JSON String to JSON Object In Flutter?

in flutter •  2 years ago 

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 client.post(url, 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};
}

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({this.name,this.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'] = this.name;
    data['age'] = this.age;
    return data;
  }
}

You must need to use this sometimes:



Map<String, dynamic> toJson() {
  return {
    jsonEncode("phone"): jsonEncode(numberPhone),
    jsonEncode("country"): jsonEncode(country),
 };
}


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"})

Conclusion:

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.

Content Resource: https://flutteragency.com/convert-json-string-to-json-object-flutter/

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!