62

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
  • 2,586
  • 7
  • 28
  • 44

8 Answers8

82

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};
}
Emmett Deen
  • 661
  • 5
  • 17
forJ
  • 4,309
  • 6
  • 34
  • 60
10

Create a model class

class User {
  int? id;
  String? name;
  String? address;

  User({this.id, this.name, this.address});

  User.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    address = json['address'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['name'] = this.name;
    data['address'] = this.address;
    return data;
  }
}

In the logic section

    String data ='{id:1, name: lorem ipsum, address: dolor set amet}';

    var encodedString = jsonEncode(data);

    Map<String, dynamic> valueMap = json.decode(encodedString);
   
    User user = User.fromJson(valueMap);

Also need to import

import 'dart:convert';

Sarath Kumar PS
  • 128
  • 2
  • 6
  • I used this solution, but I only called `json.decode` and then `User.fromJson` to properly parse into the object. Hope this helps others. – Nick N Sep 27 '22 at 01:40
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;
  }
}
Mohsen Emami
  • 2,709
  • 3
  • 33
  • 40
  • how can we use this `toJson` function? – Kamlesh Jun 21 '21 at 20:19
  • @Kamlesh you can access it as `MyModel model = new MyModel(...); final json = model.toJson();` – Mohsen Emami Jun 22 '21 at 07:15
  • will it work because `toJson()` is factory typed function? any suggestion will be welcomed. Thanks. – Kamlesh Jun 22 '21 at 17:43
  • I have a map like `userinfo = { 'name': , 'phonenumber': '9829098290', 'city': 'california' }` If I pass it it to my model like `User.fromJson(userinfo)` it does not work. I know `name` field is null. Kindly suggest how to use it to make model type value like `User.name`, `User.phonenumber`, `User.city`. Thanks. – Kamlesh Jun 22 '21 at 17:47
3
 String name =  "{click_action: FLUTTER_NOTIFICATION_CLICK, sendByImage: https://ujjwalchef.staging-server.in/uploads/users/1636620532.png, status: done, sendByName: mohittttt, id: HM11}";
  List<String> str = name.replaceAll("{","").replaceAll("}","").split(",");
  Map<String,dynamic> result = {};
  for(int i=0;i<str.length;i++){
    List<String> s = str[i].split(":");
    result.putIfAbsent(s[0].trim(), () => s[1].trim());
  }
  print(result);
}
Mohit Modh
  • 335
  • 3
  • 4
2

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"})
  • While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) 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. – rizerphe Jun 26 '20 at 18:29
1
value = "{"id":0,"customerId":null,"title":"title"}";   
var response = jsonDecode(value);
print(response['title']);
Azade Rahmati
  • 135
  • 1
  • 5
  • Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, **can you [edit] your answer to include an explanation of what you're doing** and why you believe it is the best approach? – Jeremy Caney Mar 08 '23 at 00:08
0

You must import dart:encode libary. Then use the jsonDecode function, that will produce a dynamic similar to a Map

https://api.dartlang.org/stable/2.2.0/dart-convert/dart-convert-library.html

Ernesto Campohermoso
  • 7,213
  • 1
  • 40
  • 51
0

For converting string to JSON we have to modify it with custom logic, in here first we remove all symbols of array and object and then we split text with special characters and append with key and value(for map). Please try this code snippet in dartpad.dev

import 'dart:developer';

void main() {
  String stringJson = '[{product_id: 1, quantity: 1, price: 16.5}]';

  stringJson = removeJsonAndArray(stringJson);

  var dataSp = stringJson.split(',');
  Map<String, String> mapData = {};
  for (var element in dataSp) {
    mapData[element.split(':')[0].trim()] = element.split(':')[1].trim();
  }

  print("jsonInModel: ${DemoModel.fromJson(mapData).toJson()}");
}

String removeJsonAndArray(String text) {
  if (text.startsWith('[') || text.startsWith('{')) {
    text = text.substring(1, text.length - 1);
    if (text.startsWith('[') || text.startsWith('{')) {
      text = removeJsonAndArray(text);
    }
  }
  return text;
}

class DemoModel {
  String? productId;
  String? quantity;
  String? price;

  DemoModel({this.productId, this.quantity, this.price});

  DemoModel.fromJson(Map<String, dynamic> json) {
    log('json: ${json['product_id']}');
    productId = json['product_id'];
    quantity = json['quantity'];
    price = json['price'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['product_id'] = productId;
    data['quantity'] = quantity;
    data['price'] = price;
    return data;
  }
}