在Dart中解析JSON

3
我正在尝试在Dart中将JSON解析为对象,文档使用Map类型来解析JSON响应。
关于他们的文档使用Dart处理JSON Web服务:解析JSON, 我剪辑了以下示例:
import 'dart:convert';

main() {
  String mapAsJson = '{"language":"dart"}';  // input Map of data
  Map parsedMap = JSON.decode(mapAsJson);
  print(parsedMap["language"]); // dart
}

我在我的testApp中尝试了相同的方法,但是它没有起作用。

test() {
  var url = "http://localhost/wptest/wp-json/wp/v2/posts";

  // call the web server asynchronously
  var request = HttpRequest.getString(url).then(onDataLoaded);
}

onDataLoaded(String responseText) {
  Map x = JSON.decode(responseText);
  print(x['title'].toString());
}

我遇到了这个错误

Exception: Uncaught Error: type 'List' is not a subtype of type 'Map' of 'x'.
Stack Trace:
  post.post (package:untitled8/wp/posts.dart:25:24)
  onDataLoaded (http://localhost:63342/untitled8/web/index.dart:24:15)
  _RootZone.runUnary (dart:async/zone.dart:1166)
  _Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:494)
  _Future._propagateToListeners (dart:async/future_impl.dart:577)
  _Future._completeWithValue (dart:async/future_impl.dart:368)
  _Future._asyncComplete.<anonymous closure> (dart:async/future_impl.dart:422)
  _microtaskLoop (dart:async/schedule_microtask.dart:43)
  _microtaskLoopEntry (dart:async/schedule_microtask.dart:52)
  _ScheduleImmediateHelper._handleMutation (dart:html:42567)

2
你的 JSON 文件是否以数组开头? - stwupton
@stevenupton 是的,错误是因为我的JSON是一个列表。我会在几分钟内发布答案。 - Murhaf Sousli
2个回答

2

来自服务器的JSON需要解码为Dart中的JSON,并赋值给一个类型为Stringdynamic的映射。

JSON中的必须是字符串,而它们的值对必须是dynamic类型,以便能够容纳任何值,无论是数组、整数还是布尔值。

  Map<String,dynamic> z = Map<String,dynamic>.from(JSON.decode(responseText));
    
    
    print(z.toString())

1
请在您的答案中添加更多解释以帮助读者。仅有代码的答案并不总是有用的。 - Brian Tompsett - 汤莱恩

1

文档是正确的。

//if JSON is an array (starts with '[' )

List<Map> x = JSON.decode(responseText);
print(x[0]['title']);

//if JSON is not an array (starts with '{' )

Map z = JSON.decode(responseText);
print(z['content']);
print(z['id']);
print(z['title']);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接