异常:“org.codehaus.jackson.map.JsonMappingException:无法从 START_OBJECT 令牌中反序列化 java.lang.String 的实例”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26497856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 10:01:53  来源:igfitidea点击:

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

javajsonHymanson

提问by AKIWEB

I am trying to validate a simple JSON body using Hymanson, where I am storing the JSON request as a String in "dataJson" variable.

我正在尝试使用 Hymanson 验证一个简单的 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 is) method:

SUtil.toString(InputStream is) 方法:

 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();
   }

I am learning the validation part using Hymanson but it throws error/exception on line

我正在使用 Hymanson 学习验证部分,但它在线抛出错误/异常

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

And below is the exception I am getting -

下面是我得到的例外 -

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

I wanted to learn what wrong am I doing. Any help on this would be appreciated.

我想知道我做错了什么。对此的任何帮助将不胜感激。

JSON Request:

JSON 请求:

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

回答by Sotirios Delimanolis

A JSON String maps to a Java String(and vice versa), but a JSON object does not map to a Java String, which is what you are trying to do with readValue.

JSON String 映射到 Java String(反之亦然),但 JSON 对象不映射到 Java String,而这正是您要使用的readValue.

If you're simply trying to validate the JSON, use something like

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

objectMapper.readTree(dataJson);

and ignore the result. The call will have thrown an exception if it failed to parse.

并忽略结果。如果解析失败,调用将抛出异常。

回答by Rupesh Kumar

Setting this attribute to ObjectMapper instance works,

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

 objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);