【问题标题】:Error decoding string json in flutter, "type String is not subtype of type Map"在颤振中解码字符串 json 时出错,“字符串类型不是 Map 类型的子类型”
【发布时间】:2020-10-28 07:26:03
【问题描述】:

再次对flutter有一些疑问,我需要解码从api接收到的json,但它给了我一个转换错误,这是因为json是作为反序列化字符串出现的,有一些方法可以解决这个细节。非常感谢您的帮助。

String strVar = "{ \"status\": \"1\", \"message\": \"test\",
                    \"cars\": [ { \"carId\": \"1\", \"carName\": \"Car N°1\" }, 
                                    { \"carId\": \"2\", \"carName\": \"Car N°1\" }, 
                                    { \"businessId\": \"3\", \"carName\": \"Car N°1\" }
                                   ] }"

//Here error
Map<String,dynamic> mapAPI = json.decode(strVar);

【问题讨论】:

    标签: json string rest flutter parsing


    【解决方案1】:

    要使用多行字符串文字,请将字符串用三引号 ''' 括起来,或者只使用一行。

    单行

    String strVar = "{ \"status\": \"1\", \"message\": \"test\",\"cars\": [ { \"carId\":\"1\", \"carName\": \"Car N°1\" }, { \"carId\": \"2\", \"carName\": \"Car N°1\" }, { \"businessId\": \"3\", \"carName\": \"Car N°1\" }] }";
      
    Map<String, dynamic> map = jsonDecode(strVar);
      
    print(map);
    

    多行

    String strVar = '''{ \"status\": \"1\", \"message\": \"test\",
                        \"cars\": [ { \"carId\": \"1\", \"carName\": \"Car N°1\" }, 
                                        { \"carId\": \"2\", \"carName\": \"Car N°1\" }, 
                                        { \"businessId\": \"3\", \"carName\": \"Car N°1\" }
                                       ] }'''; // String encased in 3 single-quotations at start and end
    
    Map<String, dynamic> map = jsonDecode(strVar);
    
    print(map);
    

    【讨论】:

    • 感谢解答,仅在示例模式下,字符串为单行,无法反序列化的问题。
    • 已解决,调用json.decode两次,成功了,应该是这样的:json.decode(json.decode(strVar))。如果它适用于某人,并感谢您的所有帮助。
    猜你喜欢
    • 2021-08-09
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    • 2022-01-25
    相关资源
    最近更新 更多