Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle JSON in Dart

Tags:

json

dart

I wonder how does Dart handle JSON? More specifically:

  1. Can I access item in a JSON object and when, how?
  2. Can I convert Darts data structures like Set and Maps into JSON?
  3. Can I create a new JSON, only by calling JSON.parse?
  4. How can I add new items into a JSON?
like image 327
Andreas Köberle Avatar asked Jan 23 '12 19:01

Andreas Köberle


People also ask

Does DART support JSON?

JSON is text based and human readable. The dart:convert library provides support for JSON. Use HttpRequest to dynamically load data.

How do you access JSON data in flutter?

Step 1: Create a project in Vs code, And remove the default code. Step 2: Before writing the code just add the HTTP plugin in your pubspec yaml file. Step 3: In main. dart file call the main() function , inside it run the runApp( ) method and give it an App (MyApp).


2 Answers

You can use the json property provided by the dart:convert library.

import 'dart:convert' show json;

main() {
  var encoded = json.encode([1, 2, { "a": null }]);
  var decoded = json.decode('["foo", { "bar": 499 }]');
}
like image 79
Alexandre Ardhuin Avatar answered Nov 07 '22 03:11

Alexandre Ardhuin


You might find this post of mine interesting: http://www.grobmeier.de/dart-creating-a-dynamic-list-with-dart-php-and-json-20112011.html

You need to use the JSON package (add json to pubspec.yaml):

import 'package:json/json.dart';

Here is the according spec: https://api.dartlang.org/docs/channels/stable/latest/json.html

To your questions:

  1. You can use: List result = JSON.parse( jsonData );
  2. With stringify you can turn for example a Map to JSON
  3. I am sorry, not sure on this question. You could do: JSON.parse('{key:"value"}')); or something like that
  4. You probably need to create a Map out of your JSON with parse, then add your item, and then call stringify
like image 33
Christian Avatar answered Nov 07 '22 03:11

Christian