74

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.

10 Answers 10

93

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};
}
Sign up to request clarification or add additional context in comments.

2 Comments

Yet this doesn't answer the OP question. You just explained the right way to accessing key-value pair from actual json.
The question object does not contain quotation marks, decode will fail
18

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';

1 Comment

I used this solution, but I only called json.decode and then User.fromJson to properly parse into the object. Hope this helps others.
7

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;
  }
}

4 Comments

how can we use this toJson function?
@Kamlesh you can access it as MyModel model = new MyModel(...); final json = model.toJson();
will it work because toJson() is factory typed function? any suggestion will be welcomed. Thanks.
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.
4
 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);
}

Comments

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

1 Comment

While 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.
1
value = "{"id":0,"customerId":null,"title":"title"}";   
var response = jsonDecode(value);
print(response['title']);

1 Comment

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?
1

void main() { String inputString = "{device_name: emulator_arm64, model: sdk_gphone_arm64, google, systemVersion: 11, systemName: android}";

  String? deviceName = extractValue(inputString, "device_name");
  String? systemName = extractValue(inputString, "systemName");

 if (deviceName != null) {
 print("Device Name: $deviceName");
 } else {
   print("Device Name not found");
 }

  if (systemName != null) {
    print("System Name: $systemName");
  } else {
   print("System Name not found");
 }

}

  String? extractValue(String inputString, String key) {
  int keyIndex = inputString.indexOf("$key:");

 if (keyIndex != -1) {
   int valueStartIndex = keyIndex + "$key:".length;
   int valueEndIndex = inputString.indexOf(",", valueStartIndex);

   if (valueEndIndex == -1) {
     valueEndIndex = inputString.length - 1;
   }

   return inputString.substring(valueStartIndex, valueEndIndex).trim();
 }

 return null;
}

1 Comment

format is wrong but you can copy whole code and use this only you have to change your string.
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

2 Comments

I have been try this, Map res = jsonDecode(sharedPreferences.getString('jsonString')); but I got this error: FormatException (FormatException: Unexpected character
a Map is distinct of dynamic
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;
  }
}

Comments

0

You can Use RegExpressions and after that you decode the json like this:

String jsonString = '{id:1, name: lorem ipsum, address: dolor set amet}';
// Adjust the string to a valid JSON format
jsonString = jsonString.replaceAllMapped(RegExp(r'(\w+):'), (match) => '"${match[1]}":');
jsonString = jsonString.replaceAllMapped(RegExp(r': (\w+)'), (match) => ': "${match[1]}"');
print('Adjusted JSON String: $jsonString');
// Decode the json using json.decode pre-build function
final result = json.decode(jsonString);

PS: don't forget to import 'dart:convert';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.