how to convert json string to json object in dart flutter?
Solution 1
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 json
final body = json.decode(response.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};
}
Solution 2
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 }
Ref : Dart/Flutter parse JSON string into Object
Solution 3
You can also convert JSON array to list of Objects as following:
String jsonStr = yourMethodThatReturnsJsonText();
Map<String,dynamic> d = json.decode(jsonStr.trim());
List<MyModel> list = List<MyModel>.from(d['jsonArrayName'].map((x) => MyModel.fromJson(x)));
And MyModel
is something like this:
class MyModel{
String name;
int age;
MyModel({this.name,this.age});
MyModel.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;
}
}
Solution 4
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"})
Ashtav
I am fullstack developer, I write code and also make music, I love to play guitar, drum, violin and piano.
Updated on December 06, 2021Comments
-
Ashtav over 2 years
I have string like this,
{id:1, name: lorem ipsum, address: dolor set amet}
And I need to convert that string to json, how I can do it in dart flutter? thank you so much for your help.
-
Ashtav about 5 yearsI have been try this, Map res = jsonDecode(sharedPreferences.getString('jsonString')); but I got this error: FormatException (FormatException: Unexpected character
-
Ernesto Campohermoso about 5 yearsa Map is distinct of dynamic
-
VipiN Negi almost 4 yearsYet this doesn't answer the OP question. You just explained the right way to accessing key-value pair from actual json.
-
rizerphe almost 4 yearsWhile this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.
-
Kamlesh almost 3 yearshow can we use this
toJson
function? -
Mohsen Emami almost 3 years@Kamlesh you can access it as
MyModel model = new MyModel(...); final json = model.toJson();
-
Kamlesh almost 3 yearswill it work because
toJson()
is factory typed function? any suggestion will be welcomed. Thanks. -
Kamlesh almost 3 yearsI have a map like
userinfo = { 'name': , 'phonenumber': '9829098290', 'city': 'california' }
If I pass it it to my model likeUser.fromJson(userinfo)
it does not work. I knowname
field is null. Kindly suggest how to use it to make model type value likeUser.name
,User.phonenumber
,User.city
. Thanks. -
Jason Pascoe over 2 yearsThe question object does not contain quotation marks, decode will fail