What is JSON
JSON stands for JavaScript Object Notation. It's a simple, text-based way for computers to send data to each other. Think of JSON as a digital version of a form or a table—it's a way to organize information so both sides know what each piece means.
APIs (like the weather service we will be building) almost always send data in JSON format. Your app will receive this data and turn it into objects you can use in your code.
Quick Reference
| JSON Feature | Description | Example |
|---|---|---|
| Object | A group of key-value pairs (like a dictionary) | { "temperature": 22.5, "description": "Cloudy" } |
| Array | A list of values | [ 1, 2, 3 ] or [ { "city": "Ann Arbor" }, { "city": "Detroit" } ] |
| Value | Can be a number, string, boolean, or null | "Cloudy", 22.5, true, null |
How JSON Looks
Here's a sample JSON response you might get from a weather API, I got this from entering the URL into the browser https://api.openweathermap.org/data/2.5/weather?zip=48843,US&appid=80d537a4b4cd7a3b10a3c65a70316965. This is the URL what will be created and sent by our app.
You can see it is just some key value pairs that are wrapped in objects and arrays. Our program will parse this and turn it into a Kotlin object that we can use in our code. As we progress we will see how this data is used.
{
"coord": {
"lon": -83.9248,
"lat": 42.6159
},
"weather": [
{
"id": 803,
"main": "Clouds",
"description": "broken clouds",
"icon": "04d"
}
],
"base": "stations",
"main": {
"temp": 7,
"feels_like": 4.85,
"temp_min": 6.14,
"temp_max": 7.8,
"pressure": 1009,
"humidity": 89,
"sea_level": 1009,
"grnd_level": 977
},
"visibility": 10000,
"wind": {
"speed": 3.09,
"deg": 10
},
"clouds": {
"all": 75
},
"dt": 1761834149,
"sys": {
"type": 1,
"id": 5267,
"country": "US",
"sunrise": 1761826031,
"sunset": 1761863480
},
"timezone": -14400,
"id": 0,
"name": "Howell",
"cod": 200
}
Learning Aids
Tips for Success
- Use an online tool like JSONLint to check if your JSON is valid.
- Remember: JSON keys are always in double quotes.
- JSON is case-sensitive—
Temperatureandtemperatureare different. - When you get stuck, print out the JSON response to see what it looks like.
Common Mistakes to Avoid
- Forgetting to match the JSON keys exactly in your Kotlin data class.
- Using single quotes instead of double quotes for keys or strings.
- Trying to parse invalid or incomplete JSON.
Best Practices
- Keep your data classes simple and match them to the JSON structure.
- Use meaningful names for your data class properties.
- Test with real API responses to make sure your data classes work.