如何克隆一个json对象

定义一个json对象

JObject job = new JObject();
job["age"] = 13;
job["sex"] = "male";
context.Response.Write("job:"+job.ToString() + "
");

输出结果为:job:{ "age": 13, "sex": "male" }

JObject j_clone = new JObject();
j_clone = (JObject)job.DeepClone();
j_clone["age"] = 14;
context.Response.Write("job:"+job.ToString() + "
");
job:{ "age": 13, "sex": "male" }

输出结果为:job:{ "age": 13, "sex": "male" }

这时可以发现对j_clone的属性进行修改,并未影响job。说明j_clone是克隆体。

JObject job2 = job;
job2["age"] = 15;
context.Response.Write("job:"+job.ToString() + "
");
context.Response.Write("job2:"+job2.ToString() + "
");
context.Response.Write("j_clone:"+j_clone);

输出结果为:job:{ "age": 15, "sex": "male" }

输出结果为:job2:{ "age": 15, "sex": "male" }

输出结果为:j_clone:{ "age": 14, "sex": "male" }

这时可以发现对job2进行修改的同时,job也发生了改变。说明直接赋值,不是克隆体。



你可能感兴趣的:(如何克隆一个json对象)