【问题标题】:Dart Json deserializationDart Json deserialization
【发布时间】:2022-12-27 14:09:12
【问题描述】:

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": "martinarxxxxx@gmail.com"
};

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"],
    );

   
}

【问题讨论】:

    标签: json string dart json-deserialization jsonmodel


    【解决方案1】:

    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": "john@example.com"}';
    
    dynamic json = json.decode(jsonString);
    
    print(json['name']); // Output: "John Smith"
    print(json['email']); // Output: "john@example.com"
    

    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.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-04
      • 1970-01-01
      • 2020-11-25
      • 2020-06-13
      • 1970-01-01
      • 2020-02-14
      • 2021-10-13
      • 2021-01-21
      相关资源
      最近更新 更多