无法从 VALUE_STRING 令牌中反序列化 java.util.ArrayList 的实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40147304/
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-08-11 22:26:52  来源:igfitidea点击:

Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token

javajsonarraylistHymanson

提问by Harleen

I have looked for other post in stack overflow but none of them work for me. Here is the piece of code:

我已经在堆栈溢出中寻找其他帖子,但没有一个对我有用。这是一段代码:

 public class Forward implements Serializable {
  private List<String> freq;
  public List<String> getFreq() {
    System.out.println("Print Freq::: -->  " + freq);
    return freq;
  }

  public void setFreq(List<String> freq) {
    this.freq = freq;
 }
}

The JSON string is:

JSON 字符串是:

{"forward":[{"freq":"78000000"}]}

My mapper is:

我的映射器是:

ObjectMapper mapper = new ObjectMapper();            
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
String jsonString = mapper.writeValueAsString(result);

If I remove List freq and change to String freq it works but my JSON can contain one or more freq so I need to create a List.I get exception as:

如果我删除 List freq 并更改为 String freq 它可以工作,但我的 JSON 可以包含一个或多个 freq,所以我需要创建一个 List。我得到异常:

  Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token at [Source: org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream

采纳答案by Andremoniy

DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAYworks fine in order to deserialize "freq":"78000000"fragment as value of List<String> freqlist.

DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY工作正常,以便将"freq":"78000000"片段反序列化为List<String> freq列表的值。

But you have another problem: your jsoncontains explicit array of forward. In order to deserialize this entire jsonyou need to have some kind of wrapper class, say:

但是您还有另一个问题:您json包含显式的forward. 为了反序列化这整个json你需要有某种包装类,说:

  public class ForwardWrapper {
        private List<Forward> forward;

        public List<Forward> getForward() {
            return forward;
        }

        public void setForward(List<Forward> forward) {
            this.forward = forward;
        }
    }

In this case

在这种情况下

    ForwardWrapper fw = mapper.readValue("{\"forward\":[{\"freq\":\"78000000\"}]}", ForwardWrapper.class);

will deserialize it perfectly.

将完美地反序列化它。