DEV Community

Cover image for Turing JSON Into a Dart Object - Flutter Protip 5/11/2023
Scott Beeker
Scott Beeker

Posted on

1 1 1

Turing JSON Into a Dart Object - Flutter Protip 5/11/2023

Today I wanted to talk about a great utility in the Dart language called

dart:convert
Enter fullscreen mode Exit fullscreen mode

Here is an example of how to use the dart:convert library to encode a Dart object into a JSON-encoded string:

import 'dart:convert';

void main() {
  Map<String, dynamic> person = {
    'name': 'John Doe',
    'age': 30,
    'email': 'john.doe@example.com'
  };

  String jsonEncoded = jsonEncode(person);
  print(jsonEncoded); // outputs {"name":"Hire You","age":18,"email":"me@scottbeeker.com"}
}
import 'dart:convert';

void main() {
  Map<String, dynamic> person = {
    'name': 'Hire You',
    'age': 33,
    'email': 'me@scottbeeker.com'
  };

  String jsonEncoded = jsonEncode(person);
  print(jsonEncoded); // outputs {"name":"John Doe","age":33,"email":"me@scottbeeker.com"}
}
Enter fullscreen mode Exit fullscreen mode

**
The dart:convert library in Dart provides encoders and decoders for converting between different data representations , including JSON and UTF-8. It provides a number of classes for converting between data representations, such as Codec, Decoder, Encoder, and Sink.

One common use-case of the dart:convert library is to encode or decode JSON data. You can use the jsonEncode() method to convert a Dart object into a JSON-encoded string, and the jsonDecode()method to convert a JSON-encoded string into a Dart object.

Here is an example of how to use the dart:convert library to encode a Dart object into a JSON-encoded string:
**


import 'dart:convert';

void main() {
  Map<String, dynamic> person = {
    'name': 'John Doe',
    'age': 30,
    'email': 'john.doe@example.com'
  };

  String jsonEncoded = jsonEncode(person);
  print(jsonEncoded); // outputs {"name":"John Doe","age":30,"email":"john.doe@example.com"}
}
And here is an example of how to use the dart:convert library to decode a JSON-encoded string into a Dart object:

import 'dart:convert';

void main() {
  String jsonEncoded = '{"name":"Hire You","age":33,"email":"me@scottbeeker.com"}';

  Map<String, dynamic> person = jsonDecode(jsonEncoded);
  print(person['You']); // outputs "Hire You"
}
Enter fullscreen mode Exit fullscreen mode

Follow me:
https://twitter.com/scott_beeker
https://linkedin.com/in/realscottbeeker

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more