Skip to content

Functionality to copy data from a Map and put them into an already initialized JSONObject #528

@viveksacademia4git

Description

@viveksacademia4git

I have a use case wherein I want to copy all the data (key-value pairs) of a java.util.Map object and put them into a JSONObject, which is already initialized or maybe it even contains some data. I am doing this task in the following manner:

// jsonObject already containing some data
...
     if (map != null && !map.isEmpty()) {
        for (final Entry<?, ?> e : map.entrySet()) {
            final Object key = e.getKey();
    	    if (key == null) {
    	        continue;
    	    }
            final Object value = e.getValue();
            if (value != null) {
                jsonObject.put(String.valueOf(key), value);
            }
        }
     }
...

What I am looking for is a method within the JSONObject class that perform the above task for me; like in the following code:

...
public class JSONObject {
...
    public void put(Map<?,?> map) {
    	if (map != null && !map.isEmpty()) {
	    	for (final Entry<?, ?> e : map.entrySet()) {
	            final Object key = e.getKey();
	    	    if (key == null) {
	    	        continue;
	    	    }
	            final Object value = e.getValue();
	            if (value != null) {
	                this.map.put(String.valueOf(key), wrap(value));
	            }
	        }
    	}
    }
}
...

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions