The library dart:convert
provides a built-in top-level function called jsonEncode()
that can convert a List
/Object
to a JSON string.
The following are the steps involved in converting a List
to a JSON object:
List
jsonEncode()
function, extract a JSON string from the List
.Create a list named colors
.
List<String> colors = ['Blue', 'Red', 'Black', 'Yellow', 'White', 'Pink'];
Then, convert the List
colors
to a JSON string using the dart:convert
library’s built-in jsonEncode()
function.
String jsonColors = jsonEncode(colors);
Let’s bring the pieces of code together to view the result.
import 'dart:convert';main(){//Create a listList<String> colors = ['Blue', 'Red', 'Black', 'Yellow', 'White', 'Pink'];//Use jsonEncode methodString jsonColors = jsonEncode(colors);print(jsonColors);}