简体   繁体   English

未处理的异常:“字符串”类型不是“地图”类型的子类型<String, dynamic> &#39; 将 JSON 转换为 Map 时<String, dynamic>在颤振中

[英]Unhandled Exception: type 'String' is not a subtype of type 'Map<String, dynamic>' when converting JSON to a Map<String, dynamic> in Flutter

Flask JSON page, as shown: Flask JSON 页面,如图: 页面的 JSON 输出 Alternatively, here is the JSON file:或者,这里是 JSON 文件:

["{\"atl_change_percentage\": 4914281715.26934, \"image\": \"https://assets.coingecko.com/coins/images/4934/large/0_Black-svg.png?1600757954\", \"market_cap_rank\": 987, \"max_supply\": null, \"id\": \"0chain\", \"atl\": 2.65e-09, \"price_change_24h\": -5.1138319612315e-05, \"current_price\": 0.128283, \"last_updated\": \"2022-06-23T16:10:11.148Z\", \"ath\": 5.16, \"low_24h\": 0.124866, \"market_cap_change_percentage_24h\": 0.1666, \"source\": \"\", \"atl_date\": \"2021-12-14T21:31:35.868Z\", \"symbol\": \"zcn\", \"ath_date\": \"2021-11-10T12:21:06.184Z\", \"market_cap_change_24h\": 10327.35, \"total_volume\": 14424.28, \"ath_change_percentage\": -97.47407, \"name\": \"0chain\", \"price_change_percentage_24h\": -0.03985, \"high_24h\": 0.133511, \"market_cap\": 6209045, \"circulating_supply\": 48400982.0, \"total_supply\": 400000000.0, \"fully_diluted_valuation\": null, \"roi\": null}"]

Code in flutter:颤振中的代码:

Class code:班级代码:

class CryptoInfo {
  final int market_cap_rank;
  final double ath;
  final double market_cap;
  final double low_24h;
  final double high_24h;
  final double current_price;
  final int total_volume;
  final String symbol;
  final String last_updated;
  final String id;
  final String image;
  final double circulating_supply;

  CryptoInfo({
    required this.market_cap_rank,
    required this.ath,
    required this.market_cap,
    required this.low_24h,
    required this.high_24h,
    required this.current_price,
    required this.total_volume,
    required this.symbol,
    required this.last_updated,
    required this.id,
    required this.image,
    required this.circulating_supply,
  });

  factory CryptoInfo.fromJson(Map<String, dynamic> json) {
    return CryptoInfo(
      market_cap_rank: json['market_cap_rank'] as int,
      ath: json['ath'] as double,
      market_cap: json['market_cap'] as double,
      low_24h: json['low_24h'] as double,
      high_24h: json['high_24h'] as double,
      current_price: json['current_price'] as double,
      total_volume: json['total_volume'] as int,
      symbol: json['symbol'] as String,
      last_updated: json['last_updated'] as String,
      id: json['id'] as String,
      image: json['image'] as String,
      circulating_supply: json['circulating_supply'] as double,
    );
  }
}

Code for building widget and getting data:构建小部件和获取数据的代码:

class _MainPagesState extends State<MainPages> {
  static late Future<CryptoInfo> Responses;

  @override
  void initState() {
    super.initState();
    Responses = getData();
  }

  Future<CryptoInfo> getData() async {
    final response =
        await http.get(Uri.parse('http://192.168.1.24:5000/analyze'));
    final data = await jsonDecode(response.body);


    if (response.statusCode == 200) {
      print(response.statusCode);
      print(data[0]);
      final Res = CryptoInfo.fromJson(data[0]);
      print(Res.id.toString());
      return Res;
    } else {
      throw Exception('Failed to load cryptos');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: Text("Settings"),
          centerTitle: true,
          toolbarHeight: 35,),
       body: FutureBuilder<CryptoInfo>(
        future: Responses,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return Text(snapshot.data!.id);
          } else if (snapshot.hasError) {
            return Text('${snapshot.error}');
          }

          // By default, show a loading spinner.
          return const CircularProgressIndicator();
        },
      ),
    );
  }
}

Console output:控制台输出:

I/flutter (30283): 200
I/flutter (30283): {"atl_date": "2021-12-14T21:31:35.868Z", "price_change_24h": -5.1138319612315e-05, "circulating_supply": 48400982.0, "total_supply": 400000000.0, "fully_diluted_valuation": null, "current_price": 0.128283, "max_supply": null, "roi": null, "id": "0chain", "source": "", "market_cap_rank": 987, "market_cap_change_24h": 10327.35, "ath_change_percentage": -97.47407, "last_updated": "2022-06-23T16:10:11.148Z", "atl_change_percentage": 4914281715.26934, "market_cap_change_percentage_24h": 0.1666, "atl": 2.65e-09, "symbol": "zcn", "market_cap": 6209045, "ath": 5.16, "image": "https://assets.coingecko.com/coins/images/4934/large/0_Black-svg.png?1600757954", "total_volume": 14424.28, "name": "0chain", "high_24h": 0.133511, "low_24h": 0.124866, "ath_date": "2021-11-10T12:21:06.184Z", "price_change_percentage_24h": -0.03985}
E/flutter (30283): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: type 'String' is not a subtype of type 'Map<String, dynamic>'
E/flutter (30283): #0      _MainPagesState.getData (package:crypto_app/main.dart:116:43)
E/flutter (30283): <asynchronous suspension>
E/flutter (30283): 

As shown from the console, flutter gets correct the data and can get index 0 of the data (shown with print(data[0] ). The problem is converting the data into a class CryptoInfo, and printing it.如控制台所示,flutter 获取正确的数据并可以获取数据的索引 0(显示为print(data[0] )。问题是将数据转换为类 CryptoInfo 并打印它。

After sooooo much time, I finally found the solution to this problem.经过这么多时间,我终于找到了解决这个问题的方法。

Updated function:更新功能:

Future<CryptoInfo> getData() async {
    final response =
        await http.get(Uri.parse('http://192.168.1.24:5000/analyze'));
    final data = await jsonDecode(response.body);


    if (response.statusCode == 200) {
      print(response.statusCode);
      print(jsonDecode(data[0])['id']);
      final Res = CryptoInfo.fromJson(jsonDecode(data[0]));
      print(Res.market_cap_rank);
      return Res;
    } else {
      throw Exception('Failed to load cryptos');
    }
}

You need to use jsonDecode() again if you are using a list of JSONs.如果您使用的是 JSON 列表,则需要再次使用jsonDecode() So, the line所以,线

final Res = CryptoInfo.fromJson(data[0]);

becomes:变成:

final Res = CryptoInfo.fromJson(jsonDecode(data[0]));
Future<CryptoInfo> getData() async {
    final response =
        await http.get(Uri.parse('http://192.168.1.24:5000/analyze'));
    final data = await jsonDecode(response.body);


    if (response.statusCode == 200) {
      print(response.statusCode);
      print(data[0]);
      final Res = CryptoInfo.fromJson(const JsonDecoder().convert(data[0]));
      print(Res.id.toString());
      return Res;
    } else {
      throw Exception('Failed to load cryptos');
    }
}

fromJson() takes a Map<String, dynamic> but all http requests return either a List or a String. fromJson() 采用 Map<String, dynamic> 但所有 http 请求都返回 List 或 String。 In this case, you need to use the const JsonDecoder().convert function在这种情况下,您需要使用const JsonDecoder().convert函数

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 未处理的异常:键入“列表”<dynamic> &#39; 不是类型 &#39;Map 的子类型<String, dynamic> &#39; 在颤动中如何像这样发布 json obj - Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>' in flutter how to post json obj like this 未处理的异常:“字符串”类型不是“地图”类型的子类型<string, dynamic> '</string,> - Unhandled Exception: type 'String' is not a subtype of type 'Map<String, dynamic>' E/Flutter 未处理异常:类型 _InternalLinkedHashMap<dynamic, dynamic> ' 不是类型 'Map 的子类型<string, string> ?</string,></dynamic,> - E/Flutter Unhandled Exception: type _InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, String>? 未处理的异常:键入“列表<dynamic> ' 不是 'Map 类型的子类型<string, dynamic> ' flutter 错误</string,></dynamic> - Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>' flutter error 未处理的异常:键入“列表”<dynamic> ' 不是类型 'Map 的子类型<string, dynamic> ' 在飞镖/ flutter</string,></dynamic> - Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>' in dart/ flutter 未处理的异常:类型 '_CompactLinkedHashSet<(dynamic) => Map<string, dynamic> >' 不是类型 '(Map<string, dynamic> ) => 'f' 的用户'</string,></string,> - Unhandled Exception: type '_CompactLinkedHashSet<(dynamic) => Map<String, dynamic>>' is not a subtype of type '(Map<String, dynamic>) => User' of 'f' Flutter 中的 Json 解析:列表<dynamic >不是“地图”类型的子类型<String,dynamic> &#39; - Json Parsing in Flutter: List<dynamic > is not a subtype of type 'Map<String,dynamic>' 在 dart 中解析对象(未处理的异常:类型 &#39;_InternalLinkedHashMap<dynamic, dynamic> &#39; 不是类型 &#39;Map 的子类型<String, dynamic> &#39;) - Parsing object in dart (Unhandled Exception: type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic>') 未处理的异常:键入“列表”<dynamic> ' 不是类型 'Map 的子类型<string, dynamic> ' 同时从 jsonplaceholder.typecode.com/photos 获取 Json</string,></dynamic> - Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>' While fetching Json from jsonplaceholder.typecode.com/photos 例外:“字符串”类型不是“地图”类型的子类型<String, dynamic> - Exception: type 'String' is not a subtype of type 'Map<String, dynamic>
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM