问题用 jackson 2反序列化数组为字符串
这是与Deserialize ArrayList from String using Jackson类似的问题
传入的JSON(我无法控制)具有元素“thelist”,它是一个数组。
但是,有时这是以空字符串而不是数组的形式出现的:
例如。代替“thelist”:[]
它以“thelist”的形式出现:“”
我在解析这两种情况时遇到了麻烦。
运作良好的'sample.json'文件:
{
"name" : "widget",
"thelist" :
[
{"height":"ht1","width":"wd1"},
{"height":"ht2","width":"wd2"}
]
}
这些类(class):
public class Product {
private String name;
private List<Things> thelist;
// with normal getters and setters not shown
}
public class Things {
String height;
String width;
// with normal getters and setters not shown
}
正常工作的代码:
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Test2 {
public static void main(String[] args)
{
ObjectMapper mapper = new ObjectMapper();
Product product = mapper.readValue( new File("sample.json"), Product.class);
}
}
但是,当JSON得到的是空字符串而不是数组时,即。 “thelist”:“”
我收到此错误:
com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [collection type; class java.util.ArrayList, contains [simple type, class com.test.Things]] from JSON String; no single-String constructor/factory method (through reference chain: com.test.Product["thelist"])
如果我添加这一行(它适用于Deserialize ArrayList from String using Jackson中的Ryan,并且貌似受文档支持),
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
没什么区别。
还有其他设置吗,还是需要编写自定义解串器?
如果是后者,是否有使用Jackson 2.0.4进行此操作的简单示例?
我是 jackson 的新手(也是第一次来海报,所以要彬彬有礼)。我已经做了很多搜索,但是找不到一个好的工作示例。
最佳答案
问题是,尽管单元素到数组有效,但您仍在尝试从(空)字符串到对象的转换。我假设这是您面临的问题,尽管毫无异常(exception),这很难说。
但是,结合第一个功能,还有DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT
可以解决问题。如果是这样,您将获得一个带有单个“空对象”的List
,这意味着没有值的Things
实例。
现在,理想情况下应该发生的事情是,如果仅启用ACCEPT_EMPTY_STRING_AS_NULL_OBJECT
,则可能会执行所需的操作:thelist
属性的null值。
关于json - 使用Jackson ACCEPT_SINGLE_VALUE_AS_ARRAY从字符串反序列化ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12774703/