gpt4 book ai didi

java - Jackson:忽略属性而不是抛出 JsonMappingException

转载 作者:搜寻专家 更新时间:2023-10-31 20:30:16 25 4
gpt4 key购买 nike

我有一个类需要使用 Jackson 从 JSON 反序列化。类结构如下所示:

public class A {
public B b;
}

public class B {
public List<C> c;
}

public class C {
public String s;
public Long l1;
public Long l2;
public Long l3;
}

反序列化对象大部分工作正常; except,它与错误代码互操作,当列表为空时会发出错误的值。也就是说,不是发出:

{ "b" : { "c" : [] } }

它发出:

{ "b" : { "c" : {} } }

Jackson 在遇到这种情况时会抛出这个异常:

org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
at [Source: [B@1ad5cabc; line: 1, column: 896] (through reference chain: A["b"]->B["c"])

当然,这一切都是有道理的。输入错误。

但是,本例中的空列表与任何代码都不相关;如果它是 null 我不在乎。如果无法反序列化它,有什么方法可以告诉 Jackson 忽略此属性(并存储 null)?

我试过使用自定义解串器:

public class CListDeserializer extends JsonDeserializer<List<C>>
{
public CListDeserializer() { }

@Override
public List<C> deserialize(JsonParser arg0,
DeserializationContext arg1) throws IOException,
JsonProcessingException
{
try
{
return arg0.readValueAs(new TypeReference<List<C>>(){});
}
catch (JsonMappingException jme)
{
}
return null;
}
}

如果我将注释添加到该字段:

@JsonDeserialize(using=CListDeserializer.class)
public List<C> c;

我得到的是这个异常:

org.codehaus.jackson.map.JsonMappingException: Can not instantiate value of type [simple type, class asgard.ChangeEntry] from JSON String; no single-String constructor/factory method (through reference chain: A["b"])

请注意,如果我尝试反序列化外部类型 A - 如果我提取 B 的内部序列化值,则此异常发生,并对其进行反序列化,效果很好。

最佳答案

我已经弄清楚为什么自定义反序列化器不起作用:readValueAs 方法使用 {,这会触发异常,留下 } code> 作为下一个标记。这将关闭内部对象,然后解析器将认为接下来遇到的枚举值需要作为内部类型而不是枚举类型来解析。

我明天会尝试这个,但我认为要走的路是这样的,在 deserialize 方法中:

ObjectMapper om = ...;

JsonNode node = arg0.readValueAs(JsonNode.class);
try
{
return om.readValue(node, new TypeReference<List<C>>(){});
}
catch (JsonMappingException jme)
{
}
return null;

关于java - Jackson:忽略属性而不是抛出 JsonMappingException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8827897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com