如何阻止Jackson JSON映射器隐式转换为String?

时间:2013-01-17 16:48:05

标签: java jackson

我有一个JSON数组,我想确保只包含字符串。杰克逊隐含地将整数和日期投射到弦上。我想确保JSON数组中的每个元素实际上都是一个字符串。

    Object[] badModuleArray = new Object[]{"case", 1, 2, "employee", new Date()};

    ObjectMapper objectMapper = new ObjectMapper();
    String jsonModules = objectMapper.writeValueAsString(badModuleArray);

    try
    {
        TypeFactory typeFactory = TypeFactory.defaultInstance();
        mapper.readValue(modules, typeFactory.constructCollectionType(List.class, String.class));
    }
    catch(IOException e)
    {
        logger.error("something other than strings in JSON object");

    }

在上面的例子中,我希望ObjectMapper不向字符串转换整数,日期等。如果JSON数组中的每个元素都不是字符串,我想抛出异常。这可能吗?

1 个答案:

答案 0 :(得分:2)

杰克逊正在将每个对象投射到一个字符串,因为你告诉它你想要一个List<String>

相反,请向Jackson询问List<Object>并自行检查List的内容,如果其中任何一个不是String,则抛出错误:

List list = objectMapper.readValue(jsonModules, typeFactory.constructCollectionType(List.class, Object.class));
for (Object item : list) {
    System.out.println(item + " is a: " + item.getClass());
    if (!(item instanceof String)) {
        System.out.println("Not a string!");
    }
}

对于["case",1,2,"employee",1358444552861]的JSON,我得到:

  

case是a:class java.lang.String
  1是:类java.lang.Integer
  不是字符串!
  2是:类java.lang.Integer
  不是字符串!
  employee是一个:class java.lang.String
  1358444552861是一个:类java.lang.Long
  不是字符串!