Home > Mobile >  Dart Json deserialization
Dart Json deserialization

Time:12-27

Using flutter docs am trying to learn json deserialization. But I am getting the following error "The argument type 'Map<String, String>' can't be assigned to the parameter type 'String'"

heres the code

import 'dart:convert';

User userFromJson(String str) => User.fromJson(json.decode(str));




void main() {
    
  var jsonString = {
  "name": "Martin Perumala",
  "email": "[email protected]"
};

User user = User.fromJson(jsonDecode(jsonString) as Map<String,dynamic>);

}

class User {
    User({
        required this.name,
        required this.email,
    });

    String name;
    String email;

    factory User.fromJson(Map<String, dynamic> json) => User(
        name: json["name"],
        email: json["email"],
    );

   
}

CodePudding user response:

It looks like you are trying to parse a JSON string and are encountering an error. To parse a JSON string in Flutter, you can use the json.decode() function from the dart:convert library. This function takes a string as an input and returns a dynamic object that represents the JSON structure.

Here's an example of how you can use json.decode() to parse a JSON string:

import 'dart:convert';

String jsonString = '{"name": "John Smith", "email": "[email protected]"}';

dynamic json = json.decode(jsonString);

print(json['name']); // Output: "John Smith"
print(json['email']); // Output: "[email protected]"

If you are getting the error "The argument type 'Map<String, String>' can't be assigned to the parameter type 'String'," it means that you are trying to pass a Map object as an argument to the json.decode() function, but this function expects a string. Make sure that you are passing a string to the json.decode() function, and not a Map or any other data type.

  • Related