说明:在日常开发中需要将一个对象复制出来,供另一个对象使用,则方法有

方法一:BeanUtils.copyProperties(source,target)

该方法实现浅拷贝,只复制基本对象,嵌套对象不复制

方法二:JSON.parseObject(String str,Class class)

该方法实现深拷贝,不但复制基本对象,还复嵌套对象

以下为真实案例,供日常开发使用

package com.somnus.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.somnus.custom.domain.Area;
import com.somnus.custom.domain.Employee;
import com.somnus.custom.domain.EmployeeModel;
import org.junit.Test;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Asan
 * @Date: 2024/1/11 14:39
 * @Description:演示fastjson实现复制: jar包:com.alibaba.fastjson
 * 备注: 将一个对象转换为json字符串
 * (JSONObject)JSONObject.toJSON(实体对象);//将实体对象转换为JSON对象
 * JSON.parseArray(String str,Class class);//将json字符串类型转换为list集合
 * JSON.parseObject(String str,Class class);//将json字符串类型转换为实体对象
 * JSON.parseObject(String text);//将json字符串类型转换为JOSN对象
 */
public class FastJsonTest {


    @Test
    public void testCP() {
        String dateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        //fastjson实现复制
        List<Employee> list = new ArrayList<>();
        Employee employee1 = new Employee();
        employee1.setEmpId("1001");
        employee1.setEmpName("张珊");
        employee1.setOrgId("001");
        employee1.setOrgName("常熟");
        employee1.setCreateTime(dateTime);
        employee1.setUpdateTime(dateTime);
        Employee employee2 = new Employee();
        employee2.setEmpId("1002");
        employee2.setEmpName("王五");
        employee2.setOrgId("002");
        employee2.setOrgName("苏州");
        employee2.setCreateTime(dateTime);
        employee2.setUpdateTime(dateTime);
        list.add(employee1);
        list.add(employee2);
        //将一个List<Employee> 转为List<EmployeeModel>
        List<EmployeeModel> data = JSON.parseArray(JSON.toJSONString(list), EmployeeModel.class);
        System.out.println("fastjson实现复制,复制集合:" + JSON.toJSONString(data));

        Employee employee3= new Employee();
        employee3.setEmpId("1003");
        employee3.setEmpName("李萌");
        employee3.setOrgId("003");
        employee3.setOrgName("南京");
        employee3.setCreateTime(dateTime);
        employee3.setUpdateTime(dateTime);
        EmployeeModel model=JSON.parseObject(JSON.toJSONString(employee3),EmployeeModel.class);
        System.out.println("fastjson实现复制,复制对象:"+JSON.toJSONString(model));


    }

    @Test
    public void test2() {
        //fastjson实现将java对象转换为json object对象
        Area area1 = new Area();
        area1.setCode("001");
        area1.setName("江苏省");
        JSONObject obj=JSON.parseObject(JSON.toJSONString(area1));
        System.out.println("fastjson实现将java对象转换为json object对象:" + JSON.toJSONString(obj));

    }


}

案例截图如下:

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐