32

I'm trying to load a json file from a URL and parse it within Dart. So I had tried the following code as suggested from some links when I google for it:

   HttpRequest.getString("hellknight2.js").then((response)
   {
     var model = new JSON.parse(response);
   });

However, it seems to not work anymore on Dart SDK version 0.4.3.5_r20602. What is the current best way to get a Json file mapped to an object in Dart?

Fernando
  • 1,477
  • 2
  • 14
  • 33

6 Answers6

39

Simply use json of the dart:convert package. Here is an example :

import 'dart:convert';

main() {
  final myJsonAsString = '{"a": 1, "b": "c"}';
  final decoded = json.decode(myJsonAsString);
  ....
}

See Parsing JSON for more details.

Alexandre Ardhuin
  • 71,959
  • 15
  • 151
  • 132
9

in my case

JSON.decode

didn't work.

Instead I had to use :

import 'dart:convert' as JSON;

final json=JSON.jsonDecode(myJsonAsString);
Julien
  • 3,743
  • 9
  • 38
  • 67
8

Here is my solution :) At first, you need to import the convert package:

import 'dart:convert';

var res = json.decode(response.body);

then you can get values by key, like below:

print(res["message"]);
Valentin Vignal
  • 6,151
  • 2
  • 33
  • 73
Irakli Kardava
  • 169
  • 2
  • 3
4

It depends on a lot of things.

Is the json text you get is an array or a map?

You can try with:

Map model = new parse(response);

Or

List model = new parse(response);

but you need to import JSONObject by Chris Buckett into your package

import "package:json_object/json_object.dart";

You can install it from pubspec adding this dependency

json_object
javapadawan
  • 897
  • 6
  • 12
  • 29
DaviDeMo
  • 117
  • 11
3

There's a new pub package for this:

Victor Savkin - Serializers.

I didn't use it but seems to me that it will suite you. Try it out

Alex F
  • 3,180
  • 2
  • 28
  • 40
0

you can try this package. pub: g_json

dynamic model = JSON.parse(JsonStringFromAnywhere);

final name = model['name'].stringValue;
// OR
final name = model.name;