Search code examples
javajsonclonedeep-copy

copy only the value of equal properties from one JSON to another


There is any way to copy only the value of equal properties from one JSON to another?
For example:

json1-

{
  "isMultiRow": true,
  "name": "Donny",
  "description": "Donnyboy"
}

json2-

{
  "isMultiRow": false,
  "name": "Jonny",
  "description": "Jonny boy"
  "age": "old"
  "radius":"big"
}

if I do something like json1.copy(json2) I'll get at json1 -

{
  "isMultiRow": false,
  "name": "Jonny",
  "description": "Jonny boy"
}

age and radius won't appear because they don't exist in json1.


Solution

  • You can either write a custom method that accepts 2 JSONObject and a list of fields that needs to be copied from one src JSONObject to dest JSONObject.

    private static void copy(JSONObject dest, JSONObject src, List<String> fields) {
        for (String key : fields) {
            dest.put(key, src.get(key));
        }
    }
    

    Or you can have your own custom class that extends JSONObject and have a new method copy that accepts another JSON and copies field by field.

    public class JSON extends JSONObject {
    
        private static final long serialVersionUID = 1L;
    
        public void copy(JSON other) {
            // implement copy logic by iterating over keySet etc
        }
    }
    

    NOTE: If your JSON has simple key-values then above will be very simple implementation, if your JSON string has complex objects, arrays etc then you would have add handling for each of those types and do a deep copy/override from src to dest.