简体   繁体   English

dart中的NosuchMethod用于JSON.decode

[英]NosuchMethod in dart for JSON.decode

Im trying to parse JSON from a file in dart. 我正在尝试从dart文件中解析JSON。 I've managed to read the file and print it, but when I try to convert it to JSON, it throws and error. 我设法读取并打印了文件,但是当我尝试将其转换为JSON时,它将引发错误。

file.dart: file.dart:

import 'dart:convert' as JSON;
import 'dart:io';

main() {
    final jsonAsString = new File('./text.json').readAsString().then(print); //Successful printing of json
    final json = JSON.decode(jsonAsString);


    print('$json');
}

Error: 错误:

Unhandled exception:
NoSuchMethodError: No top-level method 'JSON.decode' declared.
Receiver: top-level
Tried calling: JSON.decode(Instance of '_Future')
#0      NoSuchMethodError._throwNew (dart:core-patch/errors_patch.dart:196)
#1      main (file:///Users/ninanjohn/Trials/dartTrials/stubVerifier.dart:7:15)
#2      _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:265)
#3      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:151)

What am I missing or doing wrong here? 我在这里想念或做错了什么?

Firstly, when importing the dart:convert library you are giving it an alias called JSON . 首先,在导入dart:convert库时,您为它提供了一个名为JSON的别名。 Which means you would have to use it like; 这意味着您必须像这样使用它;

JSON.JSON.decode(jsonString);

I think you want to use show instead of as . 我认为您想使用show而不是as See this SO question for more details. 为更多的细节,以便问题。

The other issue is this line; 另一个问题是这条线。

final jsonAsString = new File('./text.json').readAsString().then(print);

You're not actually assigning a String to that variable because because the .then() method is returning a Future . 您实际上并未将String分配给该变量,因为.then()方法将返回Future

Either read the file synchronously; 要么同步读取文件;要么同步读取文件。

final jsonAsString = new File('./text.json').readAsStringSync();
print(jsonAsString);
final json = JSON.decode(jsonAsString);
print('$json');

or change it to... 或将其更改为...

new File('./text.json').readAsString().then((String jsonAsString) {
  print(jsonAsString);
  final json = JSON.decode(jsonAsString);
  print('$json');
});

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM