【问题标题】:Parsing JSON in Flutter / Dart: <RK, RV>() => Map<RK, RV> , NoSuchMethodError - (array problem?)在 Flutter / Dart 中解析 JSON: <RK, RV>() => Map<RK, RV> , NoSuchMethodError - (数组问题?)
【发布时间】:2020-07-17 12:39:58
【问题描述】:

我对 Flutter / Dart 还是有点陌生​​,而且 Ive 已经在解析 JSON 方面苦苦挣扎了一段时间。这对我来说似乎是一项艰巨的任务,尽管我认为我的 JSON 结构并不复杂。

非常感谢您的帮助。

这是我要解析的 JSON:

{
   "predictionICL":{
      "openingTimeToday":"8:00 - 23:00",
      "openingTimeTomorrow":"8:00 - 23:00",
      "percentagesToday":[
         3,
         5,
         11,
         17,
         20,
         23,
         25,
         26,
         25,
         29,
         30,
         32,
         31,
         35,
         40,
         43,
         44,
         46,
         49,
         53,
         50,
         56,
         54,
         60,
         62,
         61,
         69,
         70,
         75,
         76,
         84,
         90,
         94,
         100,
         93,
         81,
         72,
         70,
         73,
         71,
         63,
         59,
         55,
         56,
         51,
         49,
         50,
         45,
         43,
         40,
         38,
         35,
         31,
         27,
         25,
         23,
         20,
         20,
         19,
         17,
         12,
         9,
         8,
         2,
         1
      ],
      "percentagesTomorrow":[ 
         0,
         0,
         1,
         7,
         14,
         20,
         22,
         21,
         21,
         22,
         20,
         25,
         27,
         31,
         30,
         31,
         32,
         33,
         30,
         34,
         35,
         33,
         35,
         37,
         39,
         40,
         40,
         39,
         38,
         40,
         41,
         38,
         34,
         37,
         34,
         35,
         33,
         32,
         31,
         30,
         33,
         30,
         31,
         30,
         29,
         30,
         27,
         28,
         26,
         23,
         20,
         19,
         16,
         17,
         15,
         12,
         10,
         7,
         5,
         1,
         1,
         0,
         0,
         0,
         0
      ]
   },
   "predictionRandwyck":{
      "openingTimeToday":"8:00 - 23:00",
      "openingTimeTomorrow":"8:00 - 23:00",
      "percentagesToday":[
         3,
         5,
         11,
         17,
         20,
         23,
         25,
         26,
         25,
         29,
         30,
         32,
         31,
         35,
         40,
         43,
         44,
         46,
         49,
         53,
         50,
         56,
         54,
         60,
         62,
         61,
         69,
         70,
         75,
         76,
         84,
         90,
         94,
         100,
         93,
         81,
         72,
         70,
         73,
         71,
         63,
         59,
         55,
         56,
         51,
         49,
         50,
         45,
         43,
         40,
         38,
         35,
         31,
         27,
         25,
         23,
         20,
         20,
         19,
         17,
         12,
         9,
         8,
         2,
         1
      ],
      "percentagesTomorrow":[
         0,
         0,
         1,
         7,
         14,
         20,
         22,
         21,
         21,
         22,
         20,
         25,
         27,
         31,
         30,
         31,
         32,
         33,
         30,
         34,
         35,
         33,
         35,
         37,
         39,
         40,
         40,
         39,
         38,
         40,
         41,
         38,
         34,
         37,
         34,
         35,
         33,
         32,
         31,
         30,
         33,
         30,
         31,
         30,
         29,
         30,
         27,
         28,
         26,
         23,
         20,
         19,
         16,
         17,
         15,
         12,
         10,
         7,
         5,
         1,
         1,
         0,
         0,
         0,
         0
      ]
   },
   "predictionTapijn":{
      "openingTimeToday":"8:00 - 23:00",
      "openingTimeTomorrow":"8:00 - 23:00",
      "percentagesToday":[
         3,
         5,
         11,
         17,
         20,
         23,
         25,
         26,
         25,
         29,
         30,
         32,
         31,
         35,
         40,
         43,
         44,
         46,
         49,
         53,
         50,
         56,
         54,
         60,
         62,
         61,
         69,
         70,
         75,
         76,
         84,
         90,
         94,
         100,
         93,
         81,
         72,
         70,
         73,
         71,
         63,
         59,
         55,
         56,
         51,
         49,
         50,
         45,
         43,
         40,
         38,
         35,
         31,
         27,
         25,
         23,
         20,
         20,
         19,
         17,
         12,
         9,
         8,
         2,
         1
      ],
      "percentagesTomorrow":[
         0,
         0,
         1,
         7,
         14,
         20,
         22,
         21,
         21,
         22,
         20,
         25,
         27,
         31,
         30,
         31,
         32,
         33,
         30,
         34,
         35,
         33,
         35,
         37,
         39,
         40,
         40,
         39,
         38,
         40,
         41,
         38,
         34,
         37,
         34,
         35,
         33,
         32,
         31,
         30,
         33,
         30,
         31,
         30,
         29,
         30,
         27,
         28,
         26,
         23,
         20,
         19,
         16,
         17,
         15,
         12,
         10,
         7,
         5,
         1,
         1,
         0,
         0,
         0,
         0
      ]
   },
   "message":"optionalmessageString"
} 

它基本上只是数据类型 LibraryPrediction 的三个实例和一个可选的消息字符串。

数据类型 LibraryPrediction 由一个字符串“openingTimeToday”、一个字符串“openingTimeTomorrow”和两个双精度数组“percentagesToday”和“percentagesTomorrow”组成。

现在,我正在尝试从磁盘上解析 json,因为我的服务器尚未运行。 到目前为止,这是我的代码:

我有一个服务文件:

import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:test_app/models/predictions_update_model.dart';


PredictionsUpdate parseUpdate(String responseBody) {
  final jsonResponse = json.decode(responseBody).cast<Map<String, dynamic>>();

  PredictionsUpdate update = jsonResponse.map<PredictionsUpdate>((json) => PredictionsUpdate.fromJson(json));

  return update;

}

Future<PredictionsUpdate> fetchUpdate() async {

  final response = await rootBundle.loadString('lib/testJson/data.json');

  return parseUpdate(response);
}

还有一个模型文件:

class PredictionsUpdate {
  final LibraryPrediction predictionICL;
  final LibraryPrediction predictionRandwyck;
  final LibraryPrediction predictionTapijn;
  final String message;

  PredictionsUpdate({
    this.predictionICL,
    this.predictionRandwyck,
    this.predictionTapijn,
    this.message,
});

  factory PredictionsUpdate.fromJson(Map<String, dynamic> parsedJson){
    return PredictionsUpdate(
      predictionICL: LibraryPrediction.fromJson(parsedJson['predictionICL']),
      predictionRandwyck: LibraryPrediction.fromJson(parsedJson['predictionRandwyck']),
      predictionTapijn: LibraryPrediction.fromJson(parsedJson['predictionTapijn']),
      message: parsedJson['message'] as String,
    );
  }
}

class LibraryPrediction {
  final String openingTimeToday;
  final String openingTimeTomorrow;
  final List<double> percentagesToday;
  final List<double> percentagesTomorrow;

  LibraryPrediction({
    this.openingTimeToday,
    this.openingTimeTomorrow,
    this.percentagesToday,
    this.percentagesTomorrow,
  });

  factory LibraryPrediction.fromJson(Map<String, dynamic> json){
    return LibraryPrediction(
      openingTimeToday: json['openingTimeToday'] as String,
      openingTimeTomorrow: json['openingTimeTomorrow'] as String,
      percentagesToday: json['percentagesToday'] as List<double>,
      percentagesTomorrow: json['percentagesTomorrow'] as List<double>,
    );
  }
}

这就是我调用函数的方式:


Row(
              children: <Widget>[
                 RaisedButton(
                  child: Text('update'),
                  onPressed: () {
                    Future<PredictionsUpdate> futureUpdate = fetchUpdate();
                    futureUpdate.then((update)=> widget.currentNumbers = update)
                        .catchError((error) => print(error));
                  },
                ),
              ],
            ),

每当我尝试解析 JSON 时,都会收到以下错误:

flutter: NoSuchMethodError: Class '_InternalLinkedHashMap<String, dynamic>' has no instance method 'cast' with matching arguments.
Receiver: _LinkedHashMap len:4
Tried calling: cast<Map<String, dynamic>>()
Found: cast<RK, RV>() => Map<RK, RV>

我有这种感觉,当我尝试解析双数组“percentagesToday”或“percentagesTomorrow”时,错误源自某处,但我不能肯定地说,我无法从错误消息中获得更多线索。

如果我能帮我找出错误所在,我将不胜感激。

【问题讨论】:

    标签: json parsing flutter dart


    【解决方案1】:

    您可以在下面复制粘贴运行完整代码
    你可以这样做List&lt;double&gt;.from(json["percentagesToday"].map((x) =&gt; x.toDouble())),

    代码sn-p

    factory LibraryPrediction.fromJson(Map<String, dynamic> json) =>
          LibraryPrediction(
            openingTimeToday: json["openingTimeToday"],
            openingTimeTomorrow: json["openingTimeTomorrow"],
            percentagesToday: List<double>.from(
                json["percentagesToday"].map((x) => x.toDouble())),
            percentagesTomorrow: List<double>.from(
                json["percentagesTomorrow"].map((x) => x.toDouble())),
          );
    ...   
    futureUpdate.then((update) {
      print('${update.predictionIcl.openingTimeToday.toString()}');
      print('${update.message}');
      print('${update.predictionRandwyck.openingTimeTomorrow}');
    }).catchError((error) => print(error)); 
    

    输出

    I/flutter ( 7344): 8:00 - 23:00
    I/flutter ( 7344): optionalmessageString
    I/flutter ( 7344): 8:00 - 23:00
    

    完整代码

    import 'package:flutter/material.dart';
    import 'package:http/http.dart' as http;
    import 'dart:convert';
    
    PredictionsUpdate predictionsUpdateFromJson(String str) =>
        PredictionsUpdate.fromJson(json.decode(str));
    
    class PredictionsUpdate {
      LibraryPrediction predictionIcl;
      LibraryPrediction predictionRandwyck;
      LibraryPrediction predictionTapijn;
      String message;
    
      PredictionsUpdate({
        this.predictionIcl,
        this.predictionRandwyck,
        this.predictionTapijn,
        this.message,
      });
    
      factory PredictionsUpdate.fromJson(Map<String, dynamic> json) =>
          PredictionsUpdate(
            predictionIcl: LibraryPrediction.fromJson(json["predictionICL"]),
            predictionRandwyck:
                LibraryPrediction.fromJson(json["predictionRandwyck"]),
            predictionTapijn: LibraryPrediction.fromJson(json["predictionTapijn"]),
            message: json["message"],
          );
    }
    
    class LibraryPrediction {
      String openingTimeToday;
      String openingTimeTomorrow;
      List<double> percentagesToday;
      List<double> percentagesTomorrow;
    
      LibraryPrediction({
        this.openingTimeToday,
        this.openingTimeTomorrow,
        this.percentagesToday,
        this.percentagesTomorrow,
      });
    
      factory LibraryPrediction.fromJson(Map<String, dynamic> json) =>
          LibraryPrediction(
            openingTimeToday: json["openingTimeToday"],
            openingTimeTomorrow: json["openingTimeTomorrow"],
            percentagesToday: List<double>.from(
                json["percentagesToday"].map((x) => x.toDouble())),
            percentagesTomorrow: List<double>.from(
                json["percentagesTomorrow"].map((x) => x.toDouble())),
          );
    }
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: MyHomePage(title: 'Flutter Demo Home Page'),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key, this.title}) : super(key: key);
    
      final String title;
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      int _counter = 0;
    
      Future<PredictionsUpdate> fetchUpdate() async {
        String jsonString = '''
        {
       "predictionICL":{
          "openingTimeToday":"8:00 - 23:00",
          "openingTimeTomorrow":"8:00 - 23:00",
          "percentagesToday":[
             3,
             5,
             11,
             17,
             20,
             23,
             25,
             26,
             25,
             29,
             30,
             32,
             31,
             35,
             40,
             43,
             44,
             46,
             49,
             53,
             50,
             56,
             54,
             60,
             62,
             61,
             69,
             70,
             75,
             76,
             84,
             90,
             94,
             100,
             93,
             81,
             72,
             70,
             73,
             71,
             63,
             59,
             55,
             56,
             51,
             49,
             50,
             45,
             43,
             40,
             38,
             35,
             31,
             27,
             25,
             23,
             20,
             20,
             19,
             17,
             12,
             9,
             8,
             2,
             1
          ],
          "percentagesTomorrow":[ 
             0,
             0,
             1,
             7,
             14,
             20,
             22,
             21,
             21,
             22,
             20,
             25,
             27,
             31,
             30,
             31,
             32,
             33,
             30,
             34,
             35,
             33,
             35,
             37,
             39,
             40,
             40,
             39,
             38,
             40,
             41,
             38,
             34,
             37,
             34,
             35,
             33,
             32,
             31,
             30,
             33,
             30,
             31,
             30,
             29,
             30,
             27,
             28,
             26,
             23,
             20,
             19,
             16,
             17,
             15,
             12,
             10,
             7,
             5,
             1,
             1,
             0,
             0,
             0,
             0
          ]
       },
       "predictionRandwyck":{
          "openingTimeToday":"8:00 - 23:00",
          "openingTimeTomorrow":"8:00 - 23:00",
          "percentagesToday":[
             3,
             5,
             11,
             17,
             20,
             23,
             25,
             26,
             25,
             29,
             30,
             32,
             31,
             35,
             40,
             43,
             44,
             46,
             49,
             53,
             50,
             56,
             54,
             60,
             62,
             61,
             69,
             70,
             75,
             76,
             84,
             90,
             94,
             100,
             93,
             81,
             72,
             70,
             73,
             71,
             63,
             59,
             55,
             56,
             51,
             49,
             50,
             45,
             43,
             40,
             38,
             35,
             31,
             27,
             25,
             23,
             20,
             20,
             19,
             17,
             12,
             9,
             8,
             2,
             1
          ],
          "percentagesTomorrow":[
             0,
             0,
             1,
             7,
             14,
             20,
             22,
             21,
             21,
             22,
             20,
             25,
             27,
             31,
             30,
             31,
             32,
             33,
             30,
             34,
             35,
             33,
             35,
             37,
             39,
             40,
             40,
             39,
             38,
             40,
             41,
             38,
             34,
             37,
             34,
             35,
             33,
             32,
             31,
             30,
             33,
             30,
             31,
             30,
             29,
             30,
             27,
             28,
             26,
             23,
             20,
             19,
             16,
             17,
             15,
             12,
             10,
             7,
             5,
             1,
             1,
             0,
             0,
             0,
             0
          ]
       },
       "predictionTapijn":{
          "openingTimeToday":"8:00 - 23:00",
          "openingTimeTomorrow":"8:00 - 23:00",
          "percentagesToday":[
             3,
             5,
             11,
             17,
             20,
             23,
             25,
             26,
             25,
             29,
             30,
             32,
             31,
             35,
             40,
             43,
             44,
             46,
             49,
             53,
             50,
             56,
             54,
             60,
             62,
             61,
             69,
             70,
             75,
             76,
             84,
             90,
             94,
             100,
             93,
             81,
             72,
             70,
             73,
             71,
             63,
             59,
             55,
             56,
             51,
             49,
             50,
             45,
             43,
             40,
             38,
             35,
             31,
             27,
             25,
             23,
             20,
             20,
             19,
             17,
             12,
             9,
             8,
             2,
             1
          ],
          "percentagesTomorrow":[
             0,
             0,
             1,
             7,
             14,
             20,
             22,
             21,
             21,
             22,
             20,
             25,
             27,
             31,
             30,
             31,
             32,
             33,
             30,
             34,
             35,
             33,
             35,
             37,
             39,
             40,
             40,
             39,
             38,
             40,
             41,
             38,
             34,
             37,
             34,
             35,
             33,
             32,
             31,
             30,
             33,
             30,
             31,
             30,
             29,
             30,
             27,
             28,
             26,
             23,
             20,
             19,
             16,
             17,
             15,
             12,
             10,
             7,
             5,
             1,
             1,
             0,
             0,
             0,
             0
          ]
       },
       "message":"optionalmessageString"
    }
        ''';
    
        //final response = await rootBundle.loadString('lib/testJson/data.json');
        final http.Response response = http.Response(jsonString, 200);
        PredictionsUpdate payload = predictionsUpdateFromJson(response.body);
        return payload;
      }
    
      void _incrementCounter() {
        Future<PredictionsUpdate> futureUpdate = fetchUpdate();
        futureUpdate.then((update) {
          print('${update.predictionIcl.openingTimeToday.toString()}');
          print('${update.message}');
          print('${update.predictionRandwyck.openingTimeTomorrow}');
        }).catchError((error) => print(error));
    
        setState(() {
          _counter++;
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(
                  'You have pushed the button this many times:',
                ),
                Text(
                  '$_counter',
                  style: Theme.of(context).textTheme.headline4,
                ),
              ],
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: _incrementCounter,
            tooltip: 'Increment',
            child: Icon(Icons.add),
          ),
        );
      }
    }
    

    【讨论】:

    • 我知道这有点晚了,但我才看到我还没有感谢你!非常感谢,你真的帮了我大忙! :)
    猜你喜欢
    • 2021-09-15
    • 2023-03-18
    • 2021-07-10
    • 2018-09-19
    • 1970-01-01
    • 2020-11-25
    • 2013-06-28
    • 2020-02-14
    • 1970-01-01
    相关资源
    最近更新 更多