Convert String to JSON Dart/Flutter

Convert String to JSON Dart/Flutter

In the tutorial, I will introduce how to convert String to JSON Dart/Flutter using “dart:convert” library. With Dart/Flutter, for converting between different data representations (Json or UTF-8), we use “dart:convert library”.

We can use 2 methods for converting String to JSON in Dart/Flutter:

  • json.decode(str)
  • jsonDecode(str)>

Dart jsonDecode function

Parses a Dart string and returns the resulting Json object.


dynamic jsonDecode (
	String source,
	{Object? reviver(
			Object? key,
		Object? value
	)}
)

- The optional reviver function is called once for each object or list property that has been parsed during decoding.
- The key argument is either the integer list index for a list property, the string map key for object properties.

Implementation:

dynamic jsonDecode(String source,
        {Object? reviver(Object? key, Object? value)?}) =>
    json.decode(source, reviver: reviver);

Example 1 in Dart/Flutter - Convert String to JSON using json.decode function

import 'dart:convert';

void main() {
  var greeting = '{"Hello":"world"}';
  Map valueMap = json.decode(greeting);
  print(valueMap);
}

- Output:

{Hello: world}

Example 2 in Dart/Flutter - Convert String to JSON using jsonDecode function


import 'dart:convert';

void main() {
  var str = '{"first_name" : "Jack","last_name" : "Addy","gender" : "male", "location" : { "state" : "NewYork", "country" : "USA"} }';
  Map valueMap = jsonDecode(str);
  print(valueMap);
}

Output:

{first_name: Jack, last_name: Addy, gender: male, location: {state: NewYork, country: USA}}

Dart Map Tutorial – Create/Add/Delete/Iterate/Sorting

[no_toc]Dart Map Flutter Tutorial.

In the tutorial, I will introduce how to work wiht Dart Map by example coding. What will we do?
– How to Initial Dart Map by literal or constructor?
– Add new entry with Dart Map
– Iterate through Dart Map
– Update a Dart Map
– Delete with Dart Map
– Sorting a DartMap

Continue reading “Dart Map Tutorial – Create/Add/Delete/Iterate/Sorting”