Convert JSON values into comma separated values – Java

JSON is a light-weight format to store and transport data. But sometimes it is required to convert it into some other form so that the same information is compatible with new format. Recently we had to convert some JSON into comma separated values. Here is the method we used to convert the information.

Let’s say we have a JSON to store some information like device os, os version, app version code, app version name, and app name. And, we want this to convert into comma separated values using JAVA method.

{
	"app": {
		"versionCode": 15,
		"versionName": "1.4.6",
		"name": "latitude"
	},
	"os": {
		"name": "android",
		"version": "11"
	}
}

And this JSON needs to be converted into comma separated values like

app=(versionCode=15,versionName=1.4.6,name=latitude),os=(name=android,version=11)

This JAVA method getCommaSeparated() accepts JSONObject and return string in the comma separated format.

  public static String getCommaSeparated(JSONObject object) throws JSONException {
    StringBuilder builder = new StringBuilder();
    if (object != null) {
      Iterator<?> iterator = object.keys();
      while (iterator.hasNext()) {
        String key = (String) 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();
  }