两个类具有相似的字段,但它们没有父类(super class)。在我的代码中:First
和 Second
类。我需要编写方法 convertToAnother
,它将返回类 resultClassObject
的对象,其中包含对象 one
中的字段值。
这两个类都有 Json 注释。该注释的属性值等于小写的类名称(在我的代码中,类 First
具有 className = "first"
。
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.StringReader
public class Solution {
public static void main(String[] args) throws IOException {
Second s = (Second) convertOneToAnother(new First(), Second.class);
First f = (First) convertOneToAnother(new Second(), First.class);
}
public static Object convertOneToAnother(Object one, Class resultClassObject) throws IOException {
try {
ObjectMapper mapper = new ObjectMapper();
String obj = mapper.writeValueAsString(one);
obj = obj.replace("\"className\":\"" + one.getClass().getSimpleName().toLowerCase() + "\"", "\"className\":\"" + resultClassObject.getSimpleName().toLowerCase() + "\"");
return new ObjectMapper().readValue(new StringReader(obj), resultClassObject);
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property="className")
@JsonSubTypes(@JsonSubTypes.Type(value=First.class, name="first"))
public static class First {
public int i;
public String name;
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property="className")
@JsonSubTypes(@JsonSubTypes.Type(value=Second.class, name="second"))
public static class Second {
public int i;
public String name;
}
}
也许存在另一个决定?
最佳答案
使用 jackson 执行此操作的唯一正确方法是将实例编码为 json,然后解码。我建议在 java 对象级别上使用转换 - 使用 Dozer: http://dozer.sourceforge.net
关于java - 使用 json 将类转换为另一个类(Jackson 框架),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31770480/