UNIT - 3
Object Model API
Consuming & Producing JSON
https://ravulakartheek.blogspot.com/
https://ravulakartheek.blogspot.com/
What is the Object Model API?
https://ravulakartheek.blogspot.com/
https://ravulakartheek.blogspot.com/
Core Data Types
https://ravulakartheek.blogspot.com/
https://ravulakartheek.blogspot.com/
Object Model vs Streaming API
Object Model API | Streaming API |
In-memory tree | Event-based cursor |
Easy to modify | Read-only/forward |
Higher memory usage | Low memory usage |
Good for small JSON | Good for large JSON |
https://ravulakartheek.blogspot.com/
https://ravulakartheek.blogspot.com/
Consuming JSON Using the Object Model API
Steps to Read JSON (Consume)
https://ravulakartheek.blogspot.com/
https://ravulakartheek.blogspot.com/
Example JSON
{
"id": 101,
"name": "Alice",
"skills": ["Java", "JSON", "REST"]
}
https://ravulakartheek.blogspot.com/
https://ravulakartheek.blogspot.com/
Code: Consuming JSON
JsonReader reader = Json.createReader(new FileInputStream("data.json"));
JsonObject obj = reader.readObject();
int id = obj.getInt("id");
String name = obj.getString("name");
JsonArray skills = obj.getJsonArray("skills");
System.out.println(name + " has skills: " + skills);
reader.close();
https://ravulakartheek.blogspot.com/
https://ravulakartheek.blogspot.com/
Accessing Array Elements
for (JsonValue skill : skills) {
System.out.println(skill.toString());
}
https://ravulakartheek.blogspot.com/
https://ravulakartheek.blogspot.com/
Modifying JSON Tree
JsonObject updated = Json.createObjectBuilder(obj)
.add("active", true)
.build();
https://ravulakartheek.blogspot.com/
https://ravulakartheek.blogspot.com/
Producing JSON Using the Object Model API
https://ravulakartheek.blogspot.com/
https://ravulakartheek.blogspot.com/
Code: Building a JSON Object
JsonObject person = Json.createObjectBuilder()
.add("id", 102)
.add("name", "Bob")
.add("skills", Json.createArrayBuilder()
.add("Python")
.add("AI")
.add("ML"))
.build();
https://ravulakartheek.blogspot.com/
https://ravulakartheek.blogspot.com/
Writing to File
JsonWriter writer =
Json.createWriter(new FileOutputStream("output.json"));
writer.writeObject(person);
writer.close();
https://ravulakartheek.blogspot.com/
https://ravulakartheek.blogspot.com/
Output JSON
{
"id": 102,
"name": "Bob",
"skills": ["Python", "AI", "ML"]
}
https://ravulakartheek.blogspot.com/
https://ravulakartheek.blogspot.com/
Combining Consumption & Production
https://ravulakartheek.blogspot.com/
https://ravulakartheek.blogspot.com/
Advantages of Object Model API
https://ravulakartheek.blogspot.com/
https://ravulakartheek.blogspot.com/
Limitations
https://ravulakartheek.blogspot.com/
https://ravulakartheek.blogspot.com/