2

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.

9

2 Answers 2

1

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 )))

Sign up to request clarification or add additional context in comments.

Comments

1

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"

2 Comments

Plus 1 Seems fine but I have to convert JSONObject to User object which I think is a overhead.
Alternatively I converted the class members to field array and merged both the object with null check.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.