3

I'm trying to parse JSON to an object in Dart, the documentation uses Map type to parse a JSON response.

regarding to their documentation Using Dart with JSON Web Services: Parsing JSON ,I snipped the following example:

import 'dart:convert';

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

I applied the same in my testApp, however it didn't work

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());
}

I'm getting this error

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
  • 2
    Does your JSON file start with an array? Commented Nov 7, 2015 at 11:17
  • @stevenupton yes the error was because my JSON was a list. I will post the answer in minutes. Commented Nov 7, 2015 at 11:35

2 Answers 2

2

The JSON coming from the sever need to be decoded to a json in dart and assigned to a map of type String and dynamic

The keys in the json have to String while their value pair has to be of type dynamic in other to hold any value be it an array or int or bool

  Map<String,dynamic> z = Map<String,dynamic>.from(JSON.decode(responseText));
    
    
    print(z.toString())
Sign up to request clarification or add additional context in comments.

1 Comment

Please add further explanation to your answer to assist readers. Code only answers are not always helpful.
1

The documentation is correct.

//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']);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.