我正在尝试将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)
文档是正确的。
//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']);
来自服务器的JSON需要在dart中解码为json并分配给String类型和动态类型的映射
json中的键必须是String,而它们的值对必须是动态类型,以保存任何值,无论是数组还是int或bool
Map<String,dynamic> z = Map<String,dynamic>.from(JSON.decode(responseText));
print(z.toString())