Master Fastjson: Create, Modify, and Query JSON Objects in Java
This tutorial walks through using Fastjson to create, add, delete, retrieve, and manipulate JSON objects in Java, highlighting common pitfalls and showcasing advanced methods such as compute, computeIfAbsent, and custom iteration techniques.
Create
Instantiate an empty JSON object:
JSONObject fun = new JSONObject();Add
Insert a key‑value pair. The key must be a java.lang.String; the value can be any java.lang.Object (including wrapper types or collections):
fun.put("key", "value");Delete
Remove an entry by its key: fun.remove("key"); Pitfall: Do not modify the JSONObject while iterating over it, otherwise a ConcurrentModificationException may be thrown.
Get
Retrieve values using the family of getter methods:
Object obj = fun.get("key");
String s = fun.getString("key");
Integer iObj = fun.getInteger("key"); // may return null
int iVal = fun.getIntValue("key"); // returns 0 if the key is absent or the value is not a numberAll getters delegate to com.alibaba.fastjson.JSONObject#get. getInteger returns an Integer wrapper (null‑safe), while getIntValue returns a primitive int with a default of 0. Choose the method that matches the desired null‑handling semantics.
Common Operations
fun.size(); // number of entries
fun.isEmpty(); // true if no entries
fun.entrySet(); // Set<Map.Entry<String,Object>> – preferred for iteration
fun.keySet(); // Set<String>
fun.clear(); // remove all entries
fun.containsKey("key"); // check key existence
fun.containsValue("value"); // check value existencePitfall: When iterating, prefer entrySet() over keySet() to avoid concurrent‑modification issues.
Advanced Usage
// Conditional update based on current value
fun.compute("key", (k, v) -> {
return (v == null) ? "no exists" : "exists";
});
// Create a new list if the key is absent
fun.computeIfAbsent("list", k -> new ArrayList<String>());
// Modify the value only when the key is present
fun.computeIfPresent("key", (k, v) -> {
return (v == null) ? "yes" : "no";
});Fastjson also allows custom iteration patterns via lambda expressions, enabling concise transformations of JSONObject contents.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
