Today I wanted to talk about a great utility in the Dart language called
dart:convert
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"} }
**
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" }
Follow me:
https://twitter.com/scott_beeker
https://linkedin.com/in/realscottbeeker
Top comments (0)