我有一个使用泛型类型的自定义对象:
class MyObject <T> {
int x;
String y;
T customObject;
}
我正在使用jackson序列化和序列化对象。在反序列化对象时,我想知道究竟应该为类型字段传递什么。
它应该是选项1还是2?
ObjectMapper mapper = new ObjectMapper();
MyObject obj1 = objectMapper.readValue(jacksonString, MyObject.class); //option 1
MyObject obj1 = objectMapper.readValue(jacksonString, MyObject<T>.class); //option 2
如果这也是正确的方法,我很困惑。
答案 0 :(得分:0)
我无法解释你的Gson错误。您遇到的问题在您发布的代码中并不明显。
至于如何使用Jackson工作,使用评论中提到的TypeReference是正确的答案。但是,这并不能解决所有问题。你有很多选择,包括Jackson注释和/或Jackson“mixins”。但是,最容易解决这个问题的方法可能是在你的类中添加getter和setter。杰克逊将检测你的吸气剂和制定者,并适当地序列化和反序列化你的物体。
以下代码在很多方面都很简陋,但确实有效。
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
public class App {
public static void main(final String[] args) throws IOException {
final MyType myType = new MyType();
myType.setField1("blah");
myType.setField2(311);
final MyObject<MyType> myObj = new MyObject<>();
myObj.setX(10);
myObj.setY("why oh why");
myObj.setCustomObject(myType);
final ObjectMapper mapper = new ObjectMapper();
final String json = mapper.writeValueAsString(myObj);
System.out.println(json);
final TypeReference<MyObject<MyType>> typeRef = new TypeReference<MyObject<MyType>>() {};
final MyObject<MyType> myObj2 = mapper.readValue(json, typeRef);
System.out.println("x: " + myObj2.getX());
System.out.println("y: " + myObj2.getY());
System.out.println("customObject:");
System.out.println(" " + myObj2.getCustomObject().getField1());
System.out.println(" " + myObj2.getCustomObject().getField2());
}
public static class MyType {
private String field1;
private int field2;
public String getField1() { return field1; }
public void setField1(final String field1) { this.field1 = field1; }
public int getField2() { return field2; }
public void setField2(final int field2) { this.field2 = field2; }
}
public static class MyObject<T> {
private int x;
private String y;
private T customObject;
public int getX() { return x; }
public void setX(final int x) { this.x = x; }
public String getY() { return y; }
public void setY(final String y) { this.y = y; }
public T getCustomObject() { return customObject; }
public void setCustomObject(final T customObject) { this.customObject = customObject; }
}
}
这个输出是:
{"x":10,"y":"why oh why","customObject":{"field1":"blah","field2":311}}
x: 10
y: why oh why
customObject:
blah
311