EdgarDrake
EdgarDrake

Reputation: 89

Android: How to add existing JSONObject to existing key

I have a data structure like this:

source: {
    property_1: String,
    property_2: String,
    property_3: {
        property_31: String
    }
}

I want to have a function like this:

private JSONObject mergeProperty(JSONObject source, String propertyName, JSONObject newData)

in which, source is data above, propertyName = "property_3", and

newData: {
    property_32: String,
    property_33: int
}

with result of calling mergeProperty(source, "property_3", newData) as:

output: {
    property_1: String,
    property_2: String,
    property_3: {
        property_31: String,
        property_32: String,
        property_33: int
    }
}

Is there any simple method to achieve this without having to map the JSON object to HashMap first? I found no built-in JSONObject function which corelates to my problem.

Upvotes: 2

Views: 599

Answers (2)

Vinothkumar Arputharaj
Vinothkumar Arputharaj

Reputation: 4569

Try accumulate method of org.json.JSONObject.

Below code may be useful to you.

public class Test {

    public static void main(String[] args){
        System.out.println("test");
        JSONObject source = new JSONObject("{\"property_1\":\"String\",\"property_2\":\"String\",\"property_3\":{\"property_31\":\"String\"}}");
        JSONObject newData = new JSONObject("{\"property_32\":\"String\",\"property_33\":\"int\"}");
        System.out.println("Before merge :"+source.toString());
        mergeProperty(source, "property_3", newData);
        System.out.println("After merge :"+source.toString());
    }

    private static void mergeProperty(JSONObject source, String property, JSONObject newData){
        for (Object key : newData.keySet()){
            String keyStr = (String)key;
            Object keyvalue = newData.get(keyStr);
            source.getJSONObject(property).accumulate(keyStr , keyvalue);
        }
    }
}

Upvotes: 0

Anhayt Ananun
Anhayt Ananun

Reputation: 896

If I got your intention right, this code must do the job. Please, note, that this will mutate original source, so you might need to pass a copy, if mutating original one is not what you want. Also, here I assume that propertyName is on the first level of your source JSON, and is JSON, too, else this will throw a JSONException.

JSONObject mergeTarget = source.getJSONObject(propertyName);
Iterator<String> keys = newData.keys();

while (keys.hasNext()) {
    String key = keys.next();
    mergeTarget.put(key, newData.get(key));
}

Upvotes: 3

Related Questions