Flutter
JSON handling
Convert the JSON response to a model with fromJson.
Turning the response into a model
You first turn the JSON string from the API into a Map with jsonDecode, then build a model with Weather.fromJson. This gives you a type-safe object instead of a raw Map.
import 'dart:convert';
Weather parseWeather(String body) {
final json = jsonDecode(body) as Map<String, dynamic>;
return Weather.fromJson(json);
}
Nested JSON and access
Some APIs wrap weather data in nested objects. After jsonDecode you reach inner values with square brackets, then pass them to fromJson.
const body = '{"main": {"sicaklik": 21.0}, "sehir": "İzmir"}';
final json = jsonDecode(body) as Map<String, dynamic>;
final sicaklik = (json['main']['sicaklik'] as num).toDouble();
print(sicaklik); // 21.0
Exercise The parseWeather function
Write a parseWeather function: decode the body string into a Map with jsonDecode, convert it to a model with Weather.fromJson, and return it. In main, parse the given string and print the sehir field.
Show example solution
import 'dart:convert';
class Weather {
final String sehir;
final double sicaklik;
Weather(this.sehir, this.sicaklik);
factory Weather.fromJson(Map<String, dynamic> json) {
return Weather(
json['sehir'] as String,
(json['sicaklik'] as num).toDouble(),
);
}
}
Weather parseWeather(String body) {
final json = jsonDecode(body) as Map<String, dynamic>;
return Weather.fromJson(json);
}
void main() {
const body = '{"sehir": "Bursa", "sicaklik": 16.0}';
final w = parseWeather(body);
print(w.sehir);
}
Test yourself
-
What is the correct way to turn an API response into a Weather model?
- Check response.statusCode
- Call jsonEncode(body)
- Decode body with jsonDecode into a Map and pass it to Weather.fromJson
- Call http.get(body)
Show answer
Decode body with jsonDecode into a Map and pass it to Weather.fromJson — jsonDecode turns the string into a Map; Weather.fromJson builds a model from the Map. jsonEncode serializes an object, http.get takes a Uri not a string, and statusCode only shows status.
-
Decode the JSON string to a Map
import 'dart:convert';
Weather parseWeather(String body) {
final json = ____ as Map<String, dynamic>;
return Weather.fromJson(json);
}
Show answer
import 'dart:convert';
Weather parseWeather(String body) {
final json = jsonDecode(body) as Map<String, dynamic>;
return Weather.fromJson(json);
}
-
JSON processing parts
- jsonDecode(body)
- Converts the string to a Map
- as Map<String, dynamic>
- Type specification
- Weather.fromJson(json)
- Model creation
- response.body
- API response string
Next lesson: Loading state