converting string to map in dart

2020-08-09 06:08发布

问题:

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.

回答1:

That's not possible.

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

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

The string would need to look like

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


回答2:

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

I guess you are creating the string with the yourMap.toString() method, but you should rather use json.encode(yourMap), which parses your map to valid JSON, which you can the read with the json.decode(yourString) method.



回答3:

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();


回答4:

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



标签: dart flutter