how to convert json string to json object in dart flutter?
You have to use json.decode
. It takes in a json object and let you handle the nested key value pairs. I'll write you an example
import 'dart:convert';// actual data sent is {success: true, data:{token:'token'}}final response = await client.post(url, body: reqBody);// Notice how you have to call body from the response if you are using http to retrieve jsonfinal body = json.decode(response.body);// This is how you get success value out of the actual jsonif (body['success']) { //Token is nested inside data field so it goes one deeper. final String token = body['data']['token']; return {"success": true, "token": token};}
Assume that we have a simple JSON structure like this:
{ "name": "bezkoder", "age": 30}
We will create a Dart class named User
with fields: name
& age
.
class User { String name; int age; User(this.name, this.age); factory User.fromJson(dynamic json) { return User(json['name'] as String, json['age'] as int); } @override String toString() { return '{ ${this.name}, ${this.age} }'; }}
You can see factory User.fromJson()
method in the code above. It parses a dynamic object into User
object. So how to get dynamic
object from a JSON string?
We use dart:convert library’s built-in jsonDecode()
function.
import 'dart:convert';main() { String objText = '{"name": "bezkoder", "age": 30}'; User user = User.fromJson(jsonDecode(objText)); print(user);
The result will look like this.
{ bezkoder, 30 }
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"})