例外:"org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.lang.String



我正在尝试使用Jackson验证一个简单的JSON主体,我将JSON请求作为字符串存储在"dataJson"变量中。

public void unmarshal(InputStream is) throws Exception {
// this will contain my actual json string
  String dataJson= StUtil.toString(is);
  System.out.println(dataJson);
  //parse json string    
  String response = objectMapper.readValue(dataJson, String.class);
  System.out.println(response);
}

SUtil.toString(InputStream是)方法:

 public static String toString(final InputStream is) {
    final BufferedReader br = new BufferedReader(new InputStreamReader(is));
    final StringBuffer buffer = new StringBuffer();
    try {
       for (String line; (line = br.readLine()) != null; ) {
          buffer.append(line);
           }
        } catch (IOException ioe) {
        }
      return buffer.toString();
   }

我正在使用Jackson学习验证部分,但它在线上引发错误/异常

String response = objectMapper.readValue(dataJson, String.class);

下面是我得到的例外-

Exception: "org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token"

我想知道我做错了什么。如有任何帮助,我们将不胜感激。

JSON请求:

{"username" : "my_username","password" : "my_password","validation-factors":{"validationFactors":[{"name":"remote_address","value":"127.0.0.1"}]}}

JSON字符串映射到Java String(反之亦然),但JSON对象不映射到Java String,这正是您尝试使用readValue所做的。

如果您只是想验证JSON,请使用类似的东西

objectMapper.readTree(dataJson);

并忽略结果。如果调用未能解析,则会引发异常。

将此属性设置为ObjectMapper实例有效,

 objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);

相关内容

最新更新