我正在尝试将JSON解析为Dart中的对象,文档使用 Map 类型来解析JSON响应。
关于他们的文件Using Dart with JSON Web Services: Parsing 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)
答案 0 :(得分:0)
文档是正确的。
//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']);
答案 1 :(得分:0)
来自服务器的JSON需要解码为dart中的json,并分配给 String 和 dynamic
类型的映射json 中的键必须为 String ,而值对的类型必须为 dynamic 来保存任何值,无论是数组,int还是bool
Map<String,dynamic> z = Map<String,dynamic>.from(JSON.decode(responseText));
print(z.toString())