java 如何将多个第三方POJO合并为一个POJO

dgsult0t  于 2023-01-15  发布在  Java
关注(0)|答案(1)|浏览(135)

我们有多个第三方pojo,我们希望将其合并为单个pojo,并使用Jackson将该单个pojoMap到JSON。
第三方采购

public class ThirdPartyPojo1 {

    private String random1

    //public setters and getters

}
public class ThirdPartyPojo2 {

    private String random2

    //public setters and getters

}

我们想把它们结合起来形成一个单一的pojo就像-

public class ourPojo {
     private String random1;
     private String random2;

     //public setters and getters
}

我们将使用jackon将其序列化为JSON字符串。2我们如何实现这一点?

7cjasjjr

7cjasjjr1#

这是我解决你的问题的方法。我不知道是否有更好的解决方案,所以你可以参考一下。我使用ObjectReader readerForUpdating()来合并多个json源代码,但这仅限于浅复制。你可能需要另一种方法来处理更复杂的对象。以下是我的代码:

package jackson;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;

public class Test {

    static ObjectMapper mapper = new ObjectMapper();
    
    public static void main(String[] args) throws Exception {
        // Create instance and convert it to json
        ThirdPartyPojo1 obj1 = new ThirdPartyPojo1();
        obj1.setRandom1("value 1");
        String json1 = toJson(obj1);
        
        // Create instance and convert it to json
        ThirdPartyPojo2 obj2 = new ThirdPartyPojo2();
        obj2.setRandom2("value 2");
        String json2 = toJson(obj2);
        
        // Suppose the field names of ThirdPartyPojo are corresponding to ourPojo
        // Firstly, use ObjectMapper readValue() to get ThirdPartyPojo1 field i.e. random1 
        ourPojo obj3 = mapper.readValue(json1, ourPojo.class);
        
        // Secondly, use ObjectReader to update ourPojo object
        // Notes that it makes shallow copy only
        ObjectReader updater = mapper.readerForUpdating(obj3);
        // Update ourPojo from ThirdPartyPojo2 field i.e. random2
        obj3 = updater.readValue(json2);
        
        // The result displays a merging json from your single POJO
        System.out.println(toJson(obj3));
    }
    
    static String toJson(Object obj) throws JsonProcessingException {
        return mapper.writeValueAsString(obj);
    }

}

class ThirdPartyPojo1 {
    private String random1;
    // public setters and getters
}

class ThirdPartyPojo2 {
    private String random2;
    // public setters and getters
}

class ourPojo {
    private String random1;
    private String random2;
    //public setters and getters
}

玛文:

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.14.1</version>
</dependency>

相关问题