Convert JSON to comma-separated key=value pairs — Java
Recursively flatten a nested JSON object into a compact comma-separated key=value string in Java.
Sometimes you need to convert a JSON object into a compact, human-readable format — for logging, debugging, or passing metadata as a flat string. Here’s how to recursively flatten a nested JSON into comma-separated key=value pairs.
The Problem
Given this JSON:
{
"app": {
"versionCode": 15,
"versionName": "1.4.6",
"name": "latitude"
},
"os": {
"name": "android",
"version": "11"
}
}
Convert it to:
app=(versionCode=15,versionName=1.4.6,name=latitude),os=(name=android,version=11)
Nested objects are wrapped in parentheses. Flat values are printed directly.
Solution
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Iterator;
public class JsonToCommaSeparated {
public static String getCommaSeparated(JSONObject object) throws JSONException {
StringBuilder builder = new StringBuilder();
if (object != null) {
Iterator<String> iterator = object.keys();
while (iterator.hasNext()) {
String key = iterator.next();
builder.append(key).append(‘=’);
if (object.get(key) instanceof JSONObject) {
builder.append(‘(‘)
.append(getCommaSeparated((JSONObject) object.get(key)))
.append(‘)’);
} else {
builder.append(object.get(key));
}
if (iterator.hasNext()) {
builder.append(‘,’);
}
}
}
return builder.toString();
}
public static void main(String[] args) throws JSONException {
String json = """
{
"app": {
"versionCode": 15,
"versionName": "1.4.6",
"name": "latitude"
},
"os": {
"name": "android",
"version": "11"
}
}
""";
JSONObject object = new JSONObject(json);
System.out.println(getCommaSeparated(object));
// Flat JSON
String flat = """
{"city": "Bangalore", "country": "India"}
""";
System.out.println(getCommaSeparated(new JSONObject(flat)));
// Empty JSON
System.out.println(getCommaSeparated(new JSONObject("{}")));
}
}
Output
app=(versionCode=15,versionName=1.4.6,name=latitude),os=(name=android,version=11)
city=Bangalore,country=India
How it works
- Iterate through all keys in the JSON object
- For each key, check if the value is another
JSONObject- If yes, recurse and wrap the result in parentheses
- If no, append the value directly
- Add a comma between entries
The recursion handles any depth of nesting.