Introduction
We use JSON parsing to turn text data into objects our app can understand and use.
We use JSON parsing to turn text data into objects our app can understand and use.
import 'dart:convert'; var data = jsonDecode(jsonString);
jsonDecode converts a JSON string into Dart objects like Map or List.
Make sure to import 'dart:convert' to use jsonDecode.
import 'dart:convert'; var jsonString = '{"name":"Alice","age":30}'; var user = jsonDecode(jsonString);
import 'dart:convert'; var jsonString = '[1, 2, 3]'; var numbers = jsonDecode(jsonString);
This app parses a JSON string and shows the title in the app bar and the count in the center.
import 'dart:convert'; import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { const jsonString = '{"title":"Hello Flutter","count":5}'; final Map<String, dynamic> data = jsonDecode(jsonString); return MaterialApp( home: Scaffold( appBar: AppBar(title: Text(data['title'])), body: Center( child: Text('Count is: ${data['count']}'), ), ), ); } }
jsonDecode throws an error if the JSON string is invalid, so handle exceptions if needed.
The result of jsonDecode is usually a Map for JSON objects or a List for JSON arrays.
jsonDecode converts JSON text into Dart objects.
Use it to read data from APIs or files in JSON format.
Remember to import 'dart:convert' before using jsonDecode.
jsonDecode function do in Flutter?jsonDecode function takes a JSON formatted string and parses it into Dart objects such as Map or List.jsonEncode, not jsonDecode.jsonDecode in Flutter?jsonDecode function is part of the dart:convert library.jsonDecode, you must import dart:convert with import 'dart:convert';.import 'dart:convert';
void main() {
String jsonString = '{"name":"Anna","age":25}';
var user = jsonDecode(jsonString);
print(user['age']);
}jsonDecode converts the JSON string into a Map with keys 'name' and 'age'.user['age'] returns the integer 25.import 'dart:convert';
void main() {
String jsonString = '{name:"John", age:30}';
var data = jsonDecode(jsonString);
print(data['name']);
}jsonDecode will throw a FormatException.String jsonString = '[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]';
How do you parse it to get the name of the second user in Flutter?jsonDecode converts it to a List of Maps.users[1]['name'] gives 'Bob'.Pass the test and this pattern moves unknown