codepeaker
codepeaker

Reputation: 460

How to update only Non Null Json fields of a Object in an Existing Json Object in Android

Suppose, we have a User JSON response:

{
    "name": "Jack",
    "age": 28,
    "address": "Some address",
    "occupation": "Employee",
    "gender":"male"
}

With some network calls, we got another JSON response:

{ "age":"27", "address":"Some new address" }

Now, the requirement is to update the existing object with the updated fields. For e.g:

{
    "name": "Jack",
    "age":"27",
    "address":"Some new address",
    "occupation": "Employee",
    "gender":"male"
}

Notice that age and address was changed. This can be done by making null checks for small user object but doesn't look smart enough for some object like Product that will have more than 100 fields.

Looking for an efficient way to do it in Java/Kotlin.

Upvotes: 2

Views: 1957

Answers (2)

Kevin Coppock
Kevin Coppock

Reputation: 134684

A JSONObject is essentially just a map of keys/values. Assuming you only care about one level deep, a trivial approach here would be to just map the key/values from the second object (where the values are not null) to the current object.

This could be defined as an extension function on JSONObject, such as:

fun JSONObject.mergeWith(other: JSONObject): JSONObject = apply {
    other.keys()
        .asSequence()
        .associateWith(other::get)
        .filterValues { it != null }
        .forEach { (key, value) -> this.put(key, value) }
}

For example:

val firstJson = JSONObject().apply {
    put("x", 1)
    put("y", "1")
}

val secondJson = JSONObject().apply {
    put("x", 2)
    put("y", null)
}

val mergedJson = firstJson.mergeWith(secondJson) // contains x = 2, y = "1"

Upvotes: 1

Alexander Gapanowich
Alexander Gapanowich

Reputation: 592

You can use a HashMap for it, let the value name be a key, and the value will be a value ))) :

HashMap<String, String> hashMap = new HashMap<String, String>(); 


    hashMap.put("name", "Jack"); 
    hashMap.put( "age", "27");

Now, if you need to update values, just add it with the same key:

 hashMap.put( "age", "67");

Now you just need to iterate through your hashMap and get all values back, it could be like this:

 Iterator it = hashMap.entrySet().iterator();
 while (it.hasNext()) {
    Map.Entry pair = (Map.Entry)it.next();
    System.out.println(pair.getKey() + " = " + pair.getValue());
    it.remove();
 } 

And no dataBase, as you can see )))

Upvotes: 1

Related Questions