Jackson 库 1.x array if one element sometimes just a string
Jackson library 1.x array if one element sometimes just a string
我必须处理奇怪的 Json 消息。
架构中有数组,但如果只有一个元素数组就变成了字符串。
所以有时候是:
"Cisco-AVPair": [
"connect-progress=Call Up",
"nas-tx-speed=8083000",
"nas-rx-speed=8083000"
],
有时:
"Cisco-AVPair": "connect-progress=Call Up".
如果我使用 Jackson 1.8.2 如何克服这个问题
恐怕我无法控制源代码的生成,只能解析它。
我用以下方法解析它:
mapper.readValue(json, refType);
而我的类型参考是:
@JsonProperty("Cisco-AVPair")
private List<String> CiscoAVPair = new ArrayList<String>();
@JsonProperty("Cisco-AVPair")
public List<String> getCiscoAVPair() {
return CiscoAVPair;
}
@JsonProperty("Cisco-AVPair")
public void setCiscoAVPair(List<String> CiscoAVPair) {
this.CiscoAVPair = CiscoAVPair;
}
如您所见,它是字符串列表,但有时只是一个字符串。
甚至在古老的 Jackson 1.8.2 中也有一个特定的配置选项可以完全满足您的需要。
您应该将 ObjectMapper
实例配置为始终将 JSON 值反序列化为 List
,无论值是作为数组还是作为单个元素出现。请参阅 javadocs here for the deserialization feature you need to enable, and these other javadocs 了解如何在 ObjectMapper
实例上实际 activate/deactivate 功能。
ObjectMapper mapper = ...;
mapper = mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
请记住 configure()
方法 returns ObjectMapper
的另一个实例。
我必须处理奇怪的 Json 消息。
架构中有数组,但如果只有一个元素数组就变成了字符串。
所以有时候是:
"Cisco-AVPair": [
"connect-progress=Call Up",
"nas-tx-speed=8083000",
"nas-rx-speed=8083000"
],
有时:
"Cisco-AVPair": "connect-progress=Call Up".
如果我使用 Jackson 1.8.2 如何克服这个问题
恐怕我无法控制源代码的生成,只能解析它。
我用以下方法解析它:
mapper.readValue(json, refType);
而我的类型参考是:
@JsonProperty("Cisco-AVPair")
private List<String> CiscoAVPair = new ArrayList<String>();
@JsonProperty("Cisco-AVPair")
public List<String> getCiscoAVPair() {
return CiscoAVPair;
}
@JsonProperty("Cisco-AVPair")
public void setCiscoAVPair(List<String> CiscoAVPair) {
this.CiscoAVPair = CiscoAVPair;
}
如您所见,它是字符串列表,但有时只是一个字符串。
甚至在古老的 Jackson 1.8.2 中也有一个特定的配置选项可以完全满足您的需要。
您应该将 ObjectMapper
实例配置为始终将 JSON 值反序列化为 List
,无论值是作为数组还是作为单个元素出现。请参阅 javadocs here for the deserialization feature you need to enable, and these other javadocs 了解如何在 ObjectMapper
实例上实际 activate/deactivate 功能。
ObjectMapper mapper = ...;
mapper = mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
请记住 configure()
方法 returns ObjectMapper
的另一个实例。