从JSONObject浅拷贝对象

初次接触JSONObject,不得不说它非常的强悍。

阅读别人代码发现从JSONObject  A中获取的对象实例B发生改变时,JSONObjcet A也发生了变化,这说明A跟B的共同部分,指向了相同的引用,这跟java浅拷贝概念非常相似

所以我做了如下测试,发现结果确实如此。

相关代码和测试结果如下:

需要依赖的jar包(Maven)

    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.47</version>
    </dependency>

测试类

package com.JSONObject;

import com.Aes.AesUtil;
import com.alibaba.fastjson.JSONObject;

public class testJSON {

    public static void main(String[] args){
        JSONObject result = new JSONObject();
        result.put("args",args);
        result.put("aes",new AesUtil("密钥","密文",389473897));
        result.put("name","bokerr");

        System.out.println("\n    J1: "+result.toJSONString());
        System.out.println("    S1: "+result.toString());


        AesUtil aesUtil = (AesUtil) result.getObject("aes",AesUtil.class);
        aesUtil.setKey("miyao");
        aesUtil.setSecret("miwen");
        aesUtil.setNums(2333333);

        System.out.println("    J2: "+result.toJSONString());
        System.out.println("    S2: "+result.toString());

    }

}

测试实体类

package com.Aes;

public class AesUtil {
    private String key;
    private String secret;
    private int nums;

    public AesUtil(String key,String secret,int nums){
        this.key = key;
        this.secret = secret;
        this.nums = nums;
    }

    public AesUtil(){}

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }

    public int getNums() {
        return nums;
    }

    public void setNums(int nums) {
        this.nums = nums;
    }

}

输出结果:

发布了35 篇原创文章 · 获赞 11 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/bokerr/article/details/99736654