我能夠通過使用傑克遜的自定義解串器來實現這一目標:
這裏是我的MyObject對象類別。它有一個註釋,它與一個自定義解串器相關聯:
@JsonDeserialize(using = MyObjectDeserializer.class)
public class MyObject
{
public int num;
public String str;
@Override
public String toString()
{
return "{" + num + "," + str + "}";
}
}
這裏是自定義解串器。它檢查「NUM」屬性的類型是int類型的:
public class MyObjectDeserializer extends JsonDeserializer<MyObject>
{
// read current MyObject json node
JsonNode myObjectNode = jp.getCodec().readTree(jp);// this will read
// read "num" property into JsonNode and check what subclass was created
JsonNode numNode = myObjectNode.get("num");
if (numNode instanceof IntNode) { // test if value of num is int indeed
MyObject o = new MyObject();
o.num = ((IntNode)numNode).intValue(); // read int value
o.str = ((TextNode)myObjectNode.get("str")).asText(); // this is how to read string typed property
return o;
} else {
return null; // or any default/error value
}
}
現在假設以下的輸入,注意第二對象的字符串輸入「NUM」屬性:
[{"num":1,"str":"n1"}, {"num":"s","str":"n2"}, {"num":3,"str":"n3"}]
而不自定義的反序列化器,你會得到一個異常。並用它得到輸出:
[{1,n1}, null, {3,n3}]
工作就像一個魅力,非常感謝你! – stormpanda