Working with Key Pairs
Understanding JSON Key-Value Pairs
JSON key-value pairs are fundamental to representing structured data. A key is always a string, and the value can be of various types including strings, numbers, booleans, objects, or arrays.
Basic Key-Value Manipulation Techniques
1. Accessing JSON Keys
// Sample JSON object
JSONObject jsonObject = new JSONObject("{\"name\":\"John\", \"age\":30}");
// Accessing specific keys
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
2. Adding and Modifying Keys
// Creating a new JSON object
JSONObject person = new JSONObject();
// Adding key-value pairs
person.put("name", "Alice");
person.put("age", 25);
// Modifying existing key
person.put("name", "Bob");
Advanced Key Pair Operations
Nested JSON Handling
JSONObject complexJson = new JSONObject();
JSONObject address = new JSONObject();
address.put("street", "123 Main St");
address.put("city", "New York");
complexJson.put("name", "John Doe");
complexJson.put("address", address);
Key Pair Validation and Checking
JSONObject jsonObject = new JSONObject("{\"name\":\"John\", \"age\":30}");
// Checking if a key exists
boolean hasName = jsonObject.has("name");
// Checking key types
if (jsonObject.get("age") instanceof Integer) {
// Age is an integer
}
Key Manipulation Strategies
graph TD
A[JSON Key Pair Management] --> B[Create]
A --> C[Read]
A --> D[Update]
A --> E[Delete]
Common Key Pair Patterns
Operation |
Method |
Description |
Add Key |
put() |
Adds a new key-value pair |
Remove Key |
remove() |
Deletes a specific key |
Get Value |
get() |
Retrieves value by key |
Check Existence |
has() |
Checks if key exists |
Best Practices
- Always validate keys before accessing
- Handle potential null values
- Use type-safe methods
- Consider error handling
Error Handling Example
try {
JSONObject jsonObject = new JSONObject(jsonString);
String value = jsonObject.getString("key");
} catch (JSONException e) {
// Handle missing or invalid key
System.err.println("Key not found or invalid: " + e.getMessage());
}
LabEx recommends practicing these techniques to become proficient in JSON key pair manipulation. Consistent practice will help you master these essential skills in Java programming.