I have a Json file that looks like this:
[
{ \"field\":\"val\" },
....
]
I have Java object representing single object and collection o
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.
You can directly get a list through the following way:
List<ObjectClass> objs =
mapper.readValue(in, new TypeReference<List<ObjectClass>>() {});
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.