converting string to map in dart

DartFlutter

Dart Problem Overview


I wanted to convert a string to map.

String value = "{first_name : fname,last_name : lname,gender : male, location : { state : state, country : country, place : place} }"

into

Map = {
first_name : fname,
last_name : lname,
gender : male,
location = {
  state : state, 
  country : country, 
  place : place
 }
}

How do I convert the string into a map<String, dynamic> where the value consists of string, int, object, and boolean?

I wanted to save the string to a file and obtain the data from the file.

Dart Solutions


Solution 1 - Dart

That's not possible.

If you can change the string to valid JSON, you can use

import 'dart:convert';
...
Map valueMap = json.decode(value);
// or
Map valueMap = jsonDecode(value);

The string would need to look like

{"first_name" : "fname","last_name" : "lname","gender" : "male", "location" : { "state" : "state", "country" : "country", "place" : "place"} }

Solution 2 - Dart

You would have to change the way you create the string.

I'm guessing you are creating the string using the yourMap.toString() method. You should rather use json.encode(yourMap), which converts your map to valid JSON, which you can the parse with json.decode(yourString).

Solution 3 - Dart

create two objects

class User {
  final String firstName;
  final String lastName;
  final String gender;
  final location;

  User({
    this.firstName,
    this.lastName,
    this.gender,
    this.location,
  });

  User.fromJson(Map json)
      : firstName = json['firstName'],
        lastName = json['lastName'],
        gender = json['gender'],
        location = Location.fromJson(json['location']);
}

class Location {
  final String state;
  final String country;
  final String place;

  Location({
    this.state,
    this.country,
    this.place,
  });

  Location.fromJson(Map json)
      : state = json['state'],
        country = json['country'],
        place = json['place'];
}

then use it like this

var user = User.fromJson(value);
print(user.firstName);

or convert it to list like this

var user = User.fromJson(value).toList();

Solution 4 - Dart

Make a wrapper class for the location where you define the methods fromMap, toMap

Solution 5 - Dart

you can do like this ->

import 'dart:convert'; ... > if your data like this ** {'bus1':'100Tk','bus2':'150TK','bus3':'200TK'}

**;

then you can do like this ->

Map valueMap = json.decode(value);

// or

Map valueMap = jsonDecode(value);

> or if like this ->var data = {'1':'100TK','2':'200TK','3':'300TK'};

var dataSp = data.split(',');
Map<String,String> mapData = Map();
dataSp.forEach((element) => mapData[element.split(':')[0]] = element.split(':')[1]);

> Note: Map first value was Int that's why I did that.

Solution 6 - Dart

Use below method
just pass String json data it will give Map data

jsonStringToMap(String data){
      List<String> str = data.replaceAll("{","").replaceAll("}","").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());
      }
      return result;
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaniel ManaView Question on Stackoverflow
Solution 1 - DartGünter ZöchbauerView Answer on Stackoverflow
Solution 2 - DartleodrieschView Answer on Stackoverflow
Solution 3 - DartPatrioticcowView Answer on Stackoverflow
Solution 4 - DartdoomkinView Answer on Stackoverflow
Solution 5 - DartRasel KhanView Answer on Stackoverflow
Solution 6 - DartMohit ModhView Answer on Stackoverflow