如何从 Jackson 中的数组开始反序列化 JSON 文件?

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

How to deserialize JSON file starting with an array in Hymanson?

jsonHymanson

提问by pixel

I have a Json file that looks like this:

我有一个看起来像这样的 Json 文件:

[
    { "field":"val" },
....
]

I have Java object representing single object and collection of them:

我有代表单个对象和它们的集合的 Java 对象:

public class Objects{

    public Collection<List> myObject;
}

I would like to deserialize JSON using ObjectMapper.

我想使用ObjectMapper.

ObjectMapper mapper = new ObjectMapper();
mapper.readValue(in, Objects.class);

But I get:

但我得到:

11-24 23:19:19.828: W/UpdateService(6084): org.codehaus.Hymanson.map.JsonMappingException: 
Can not deserialize instance of com.project.my.Objects out of START_ARRAY token

回答by dmon

Try

尝试

   mapper.readValue(in, ObjectClass[].class);

Where ObjectClass is something like:

其中 ObjectClass 是这样的:

  public class ObjectClass {
    String field;

    public ObjectClass() { }

    public void setField(String value) {
      this.field = value;
    }
  }

Note: in your posted version of the Objectsclass, you're declaring a Collection of Lists (i.e. a list of lists), which is not what you want. You probably wanted a List<ObjectClass>. However, it's much simpler to just do YourObject[].classwhen deserializing with Hymanson, and then converting into a list afterwards.

注意:在您发布的Objects课程版本中,您声明了一个列表集合(即列表列表),这不是您想要的。你可能想要一个List<ObjectClass>. 但是,YourObject[].class在使用 Hymanson 反序列化然后转换为列表时要简单得多。

回答by Han He

You can directly get a list through the following way:

您可以通过以下方式直接获取列表:

List<ObjectClass> objs =  
    mapper.readValue(in, new TypeReference<List<ObjectClass>>() {});

回答by StaxMan

Passing an array or List type works, as @dmon answered.

正如@dmon 回答的那样,传递数组或列表类型有效。

For sake of completeness, there is also an incremental approach if you wanted to read contents one-by-one:

为了完整起见,如果您想逐个阅读内容,还有一种增量方法:

Iterator<Objects> it = mapper.reader(Objects.class).readValues(in);
while (it.hasNext()) {
  Objects next = it.next();
  // ... process it
}

This is useful if you have huge lists or sequences of objects; either with enclosing JSON Array, or just root-level values separated by spaces or linefeeds.

如果您有大量的对象列表或序列,这很有用;要么带有封闭的 JSON 数组,要么只是由空格或换行符分隔的根级值。