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

后端 未结 3 1812
我寻月下人不归
我寻月下人不归 2020-12-18 18:43

I have a Json file that looks like this:

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

I have Java object representing single object and collection o

相关标签:
3条回答
  • 2020-12-18 19:21

    Try

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

    Where ObjectClass is something like:

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

    Note: in your posted version of the Objects class, 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[].class when deserializing with Jackson, and then converting into a list afterwards.

    0 讨论(0)
  • 2020-12-18 19:25

    You can directly get a list through the following way:

    List<ObjectClass> objs =  
        mapper.readValue(in, new TypeReference<List<ObjectClass>>() {});
    
    0 讨论(0)
  • 2020-12-18 19:34

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

    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.

    0 讨论(0)
提交回复
热议问题