Click here to Skip to main content
15,921,694 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to copy one json say json1 to another json say json2. It seems values get overwrited ie., if am putting value in one key say key1 of json1. key1 value of json2 get overwritted.

What I have tried:

Works :
JSONObject json1 = new JSONObject();
json1.put("a",new JSONObject().put("c",1)).put("b","2");
JSONObject json2 = new JSONObject();
Iterator itr = json1.keys();//copying json from source to destinationJson
while(itr.hasNext()) {
String key = (String) itr.next();
json2.put(key, json1.get(key));
}
json1.put("b",3);
out.print("json1"+json1);
out.print("json2"+json2);

here , value b didnot get overwrite .

but if put value in c. It get overwritted. seems a of two jsons share same memory.

JSONObject subjson = json1.getJSONObject("a");
subjson.put("a",2);
out.print("json1"+json1);
out.print("json2"+json2);

So how can i solve it ? :( ..
Posted
Updated 17-May-17 5:32am
v2

1 solution

You talk about deep and shallow cloning. Here is more information. Understanding Object Cloning in Javascript - Part. I[^]
JavaScript
function naiveShallowCopy( original )  
{
    // First create an empty object
    // that will receive copies of properties
    var clone = {} ;

    var key ;

    for ( key in original )
    {
        // copy each property into the clone
        clone[ key ] = original[ key ] ;
    }

    return clone ;
}
 
Share this answer
 
Comments
moyna coder 17-May-17 13:02pm    
Am asking in java
moyna coder 17-May-17 13:14pm    
and that nly i have tried .

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900