json - 使用Jackson ACCEPT_SINGLE_VALUE_AS_ARRAY从字符串反序列化ArrayList

标签 json serialization jackson

问题用 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/

相关文章:

java - 使用 Spring MVC 如何为 java 8 LocalDateTime 添加自定义 JsonSerializer?

java - 如何在 java 中创建一个复杂的 json 对象?

c# - 在 C# 中反序列化 JSON 而不创建类

c# - Json.Net 在 ApiController 中序列化派生类而不是基类

c# - 序列化静态类?

java - java中的OpenCV Mat对象序列化

ruby-on-rails - 将 "complex"JSON 数据转换为散列

java - JPQL @query 与 json 的关系表

php - 如何放入JSON对象非英文字母?

jaxb - 在 Jersey 使用 Gson 而不是 Jackson