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}}


By grokonez | May 9, 2021.


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*