Murhaf Sousli
Murhaf Sousli

Reputation: 13286

Parsing JSON in Dart

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)

Upvotes: 3

Views: 3815

Answers (2)

ikben
ikben

Reputation: 4625

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

Upvotes: 2

Murhaf Sousli
Murhaf Sousli

Reputation: 13286

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

Upvotes: 1

Related Questions