使用Jackson ACCEPT_SINGLE_VALUE_AS_ARRAY从String反序列化ArrayList

use*_*784 9 serialization json jackson

问题使用Jackson 2将数组反序列化为字符串

这是使用Jackson从String反序列化ArrayList的类似问题

传入的JSON(我无法控制)有一个元素'thelist',它是一个数组.但是,有时它会以空字符串而不是数组形式出现:

例如.而不是"thelist":[]
它以"thelist"形式出现:""

我在解析这两种情况时遇到了麻烦.

"sample.json"文件的正常工作:

{
   "name" : "widget",
   "thelist" : 
    [
       {"height":"ht1","width":"wd1"}, 
       {"height":"ht2","width":"wd2"}
    ]
}
Run Code Online (Sandbox Code Playgroud)

课程:

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
}
Run Code Online (Sandbox Code Playgroud)

工作正常的代码:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,当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"])
Run Code Online (Sandbox Code Playgroud)

如果我添加这一行(对于Ryan来说,使用Jackson从String反序列化ArrayList并且看似文档支持),

mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
Run Code Online (Sandbox Code Playgroud)

没什么区别.

是否有其他设置,或者我是否需要编写自定义反序列化器?
如果是后者,是否有一个简单的例子用Jackson 2.0.4做到这一点?
我是杰克逊的新手(和第一次海报,所以要温柔).我做了很多搜索,但找不到一个好的工作实例.

Sta*_*Man 4

问题是,尽管单元素到数组有效,但您仍在尝试从(空)字符串转换为对象。我假设这就是您面临的问题,尽管很难说无一例外。

但与第一个功能相结合,还有DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT一个可能会起作用。如果是这样,您将得到一个List带有单个“空对象”的对象,这意味着Things没有值的实例。

现在理想情况下应该发生的是,如果您仅启用ACCEPT_EMPTY_STRING_AS_NULL_OBJECT,则可能会执行您想要的操作:属性为空值thelist