I use a JSON library called JSONObject
(I don\'t mind switching if I need to).
I know how to iterate over JSONArrays
, but when I parse JSO
I once had a json that had ids that needed to be incremented by one since they were 0-indexed and that was breaking Mysql auto-increment.
So for each object I wrote this code - might be helpful to someone:
public static void incrementValue(JSONObject obj, List keysToIncrementValue) {
Set keys = obj.keySet();
for (String key : keys) {
Object ob = obj.get(key);
if (keysToIncrementValue.contains(key)) {
obj.put(key, (Integer)obj.get(key) + 1);
}
if (ob instanceof JSONObject) {
incrementValue((JSONObject) ob, keysToIncrementValue);
}
else if (ob instanceof JSONArray) {
JSONArray arr = (JSONArray) ob;
for (int i=0; i < arr.length(); i++) {
Object arrObj = arr.get(0);
if (arrObj instanceof JSONObject) {
incrementValue((JSONObject) arrObj, keysToIncrementValue);
}
}
}
}
}
usage:
JSONObject object = ....
incrementValue(object, Arrays.asList("id", "product_id", "category_id", "customer_id"));
this can be transformed to work for JSONArray as parent object too