从API反序列化JSON值:大括号与方括号的区别
Hey there! Let's break down how to handle curly braces {} and square brackets [] when deserializing that weather API JSON you're working with—this is a super common gotcha, so let's make it clear with your specific response example.
{} vs Square Brackets [] in JSON Deserialization First, let's start with what these symbols actually represent in JSON, since that's the core of getting deserialization right:
1. Curly Braces {}: JSON Objects
Curly braces define a key-value pair object—think of this like a dictionary (in Python) or a custom class instance (in Java/C#), where every value is tied to a named, unique key.
Looking at your weather API response:
- The entire top-level structure is an object:
{"coord": {...}, "weather": [...], "main": {...}, ...} - Fields like
coord({"lon":-85.6,"lat":43.05}) andmain({"temp":277.33,"pressure":1010,...}) are nested objects.
Deserializing Objects
In dynamic languages like Python, objects become dictionaries, and you access values via their keys:
import json # Parse the JSON string into a Python dict response_data = json.loads(your_api_json_string) # Access nested object values using key names longitude = response_data["coord"]["lon"] current_temp = response_data["main"]["temp"]
In statically typed languages like Java (using Jackson), you'll create matching classes to map the object structure:
// Class for the nested "coord" object public class Coord { private double lon; private double lat; // Getters and setters } // Top-level class matching the full API response public class WeatherResponse { private Coord coord; private List<Weather> weather; // We'll get to this next! private Main main; // Other fields + getters/setters } // Deserialize using Jackson's ObjectMapper ObjectMapper mapper = new ObjectMapper(); WeatherResponse response = mapper.readValue(yourApiJsonString, WeatherResponse.class); double latitude = response.getCoord().getLat();
2. Square Brackets []: JSON Arrays
Square brackets represent an ordered list of values—these can be objects, strings, numbers, or even other arrays. In your response, the weather field is an array: [{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}] (even though it only has one item here, it's still an array).
Deserializing Arrays
In Python, arrays become lists, and you access items via their index position:
# Get the weather array (a list of dicts) weather_entries = response_data["weather"] # Access the first (and only) entry in the array first_weather = weather_entries[0] cloud_description = first_weather["description"] # "broken clouds"
In Java, you'll map arrays to a List (or array) of the corresponding object type:
// Class for items in the "weather" array public class Weather { private int id; private String main; private String description; private String icon; // Getters and setters } // In the WeatherResponse class, the weather field is a List<Weather> private List<Weather> weather; // After deserialization, access via index String weatherMain = response.getWeather().get(0).getMain(); // "Clouds"
Critical Differences to Avoid Mistakes
- Objects need key access: You can't pull values from an object using an index (like
[0])—you have to use the exact key name (case-sensitive!). - Arrays need index access: Even if an array has only one item, you can't access it via a key—you have to target its position in the list.
- Mixing them causes errors: If you try to map an array to a single object (e.g., declaring
private Weather weatherinstead ofList<Weather> weatherin Java), your deserialization library will throw an error like "Cannot deserialize instance ofWeatherout of START_ARRAY token".
内容的提问来源于stack exchange,提问作者babernethy

