zoukankan      html  css  js  c++  java
  • Java对象深复制

    用的是Json转换

    List<CpStage> cpStageListOld = findCpStageByCpId(cpId);
    String cpStageListJson = JsonUtils.toJson(cpStageListOld);
    List<CpStage> cpStageList = JsonUtils.fromJsonToList(cpStageListJson, CpStage.class);

    JsonUtils.java

    import com.fasterxml.jackson.databind.JavaType;
    import com.fasterxml.jackson.databind.JsonNode;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.type.TypeFactory;
    import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector;
    
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    
    public class JsonUtils {
        public static <T> T fromJson(String json, Class<T> clz) {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()));
            try {
                return objectMapper.readValue(json, clz);
            } catch (IOException e) {
                throw new RuntimeException("Failed to deserialize json: " + e.getMessage(), e);
            }
        }
    
        public static JsonNode fromJsonToNode(String json) {
            ObjectMapper mapper = new ObjectMapper();
            try {
                return mapper.readTree(json);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    
        public static <T> List<T> fromJsonToList(String json, Class<T> clz) {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()));
            try {
                JavaType javaType = TypeFactory.defaultInstance().constructCollectionType(ArrayList.class, clz);
                return objectMapper.readValue(json, javaType);
            } catch (IOException e) {
                throw new RuntimeException("Failed to deserialize json to List: " + e.getMessage(), e);
            }
        }
    
        public static String toJson(Object object){
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()));
            try {
                return objectMapper.writeValueAsString(object);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
  • 相关阅读:
    深度学习(dropout)
    centos 常见软件安装
    最近读的书 与论文
    如何理解反向传播 Backpropagation 梯度下降算法要点
    ubuntu 15 安装cuda,开启GPU加速
    快速排序算法
    Linux网络中接收 "二进制" 流的那些事 --- 就recv的返回值和strlen库函数进行对话
    linux源码升级编译内核
    C/C++中慎用宏(#define)
    Qt之hello world
  • 原文地址:https://www.cnblogs.com/ms-grf/p/7344891.html
Copyright © 2011-2022 走看看