As I indicated in the comment to the question here is the test that shows how to do this:

public class JSONTest {

  public static class FullyTypedThing {
    public int id;
    public String name;
    public List<Photos> photos = Lists.newArrayList();
    public String username;

    public static class Photos {
      public String name;
      public String url;
    }
  }

  private static final String json = "[ { \"id\" : 33147,    \"name\" : \"Refinancing\", \"photos\" : [ {"
    + "\"name\" : \"347.png\", \"url\" : \"/loans/568/photos/092\"  } ],"
    + "\"username\" : \"zach1985\"} , {  \"id\" : 7693,  \"name\" : \"Stuff\","
    + "\"photos\" : [ {  \"name\" : \"newpic1.png\",  \"url\" : \"/loans/123446/photos/890\"  } ],"
    + "\"username\" : \"sengaia\"  } ]";

  @Test
  public void roundtrip() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    List<FullyTypedThing> res = Lists.newArrayList(
      mapper.readValue(json, FullyTypedThing[].class));
    assertEquals(2, res.size());
    assertEquals(33147, res.get(0).id);
    assertEquals("Refinancing", res.get(0).name);
    assertEquals("347.png", res.get(0).photos.get(0).name);
    assertEquals("/loans/568/photos/092", res.get(0).photos.get(0).url);
    assertEquals(7693, res.get(1).id);
    assertEquals("Stuff", res.get(1).name);
    assertEquals("newpic1.png", res.get(1).photos.get(0).name);
    assertEquals("/loans/123446/photos/890", res.get(1).photos.get(0).url);

    assertEquals("[{\"id\":33147,\"name\":\"Refinancing\",\"photos\":"
      + "[{\"name\":\"347.png\",\"url\":\"/loans/568/photos/092\"}],"
      + "\"username\":\"zach1985\"},{\"id\":7693,\"name\":\"Stuff\","
      + "\"photos\":[{\"name\":\"newpic1.png\",\"url\":\"/loans/123446/photos/890\"}],"
      + "\"username\":\"sengaia\"}]", mapper.writeValueAsString(res));

  }
}
Answer from Oleg Sklyar on Stack Overflow
🌐
YouTube
youtube.com › watch
Serialization & Deserialization - Array of Objects - Java - YouTube
Code can be downloaded from https://codespindle.com/Java/Java_objectinputstream_Objectoutputstream.htmlIn this session we will look at how to serialize and d...
Published: April 29, 2021
🌐
Baeldung
baeldung.com › home › json › jackson › jackson – unmarshall to collection/array
Jackson - Unmarshall to Collection/Array | Baeldung
April 26, 2024 - Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time. ... This tutorial will show how to deserialize a JSON Array to a Java Array or Collection with Jackson 2. If you want to dig deeper and learn other cool things you can do with the Jackson 2 – head on over to the main Jackson tutorial. ... @Test public void givenJsonArray_whenDeserializingAsArray_thenCorrect() throws JsonParseException, JsonMappingException, IOException { ObjectMapper mapper = new ObjectMapper(); List<MyDto> listOfDtos = Lists.newArrayList( new MyDto("a"
Discussions

How to Deserialize Array of JSON Objects in Java - Stack Overflow
Hi I am also doing in a similar way like I have array of json objects but getting this error com.fasterxml.jackson.databind.JsonMappingException: (was java.io.IOException) (through reference chain: java.lang.Object[][0])↵ 2021-02-11T03:24:56.49Z+00:00 ... When response is a JSON Object you can use default bean deserialiser... More on stackoverflow.com
🌐 stackoverflow.com
September 26, 2019
Help deserializing a JSON array of arrays in DSL-JSON
I have no knowledge of dsl-json, but the ObjectMapper error is clear. Your input data is a List>. Is this really how it's supposed to look? Usually in Java you would create a class or record representing the data model and use mapper.readValue(jsonString, YourRecord.class), but with this type of data it's going to be tricky. Edit. Maybe you can deserialize it to Object[][].class More on reddit.com
🌐 r/javahelp
26
1
September 1, 2022
java - How to use Jackson to deserialise an array of objects - Stack Overflow
The Jackson data binding documentation indicates that Jackson supports deserialising "Arrays of all supported types" but I can't figure out the exact syntax for this. For a single object I would do More on stackoverflow.com
🌐 stackoverflow.com
java - How to deserialize array into an object? - Stack Overflow
Jackson will instantiate AdDimensionDeserializer and use the instance to deserialize the JSON array elements into an instance(s) of AdDimension. More on stackoverflow.com
🌐 stackoverflow.com
June 9, 2017
Top answer
1 of 1
2

As I indicated in the comment to the question here is the test that shows how to do this:

public class JSONTest {

  public static class FullyTypedThing {
    public int id;
    public String name;
    public List<Photos> photos = Lists.newArrayList();
    public String username;

    public static class Photos {
      public String name;
      public String url;
    }
  }

  private static final String json = "[ { \"id\" : 33147,    \"name\" : \"Refinancing\", \"photos\" : [ {"
    + "\"name\" : \"347.png\", \"url\" : \"/loans/568/photos/092\"  } ],"
    + "\"username\" : \"zach1985\"} , {  \"id\" : 7693,  \"name\" : \"Stuff\","
    + "\"photos\" : [ {  \"name\" : \"newpic1.png\",  \"url\" : \"/loans/123446/photos/890\"  } ],"
    + "\"username\" : \"sengaia\"  } ]";

  @Test
  public void roundtrip() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    List<FullyTypedThing> res = Lists.newArrayList(
      mapper.readValue(json, FullyTypedThing[].class));
    assertEquals(2, res.size());
    assertEquals(33147, res.get(0).id);
    assertEquals("Refinancing", res.get(0).name);
    assertEquals("347.png", res.get(0).photos.get(0).name);
    assertEquals("/loans/568/photos/092", res.get(0).photos.get(0).url);
    assertEquals(7693, res.get(1).id);
    assertEquals("Stuff", res.get(1).name);
    assertEquals("newpic1.png", res.get(1).photos.get(0).name);
    assertEquals("/loans/123446/photos/890", res.get(1).photos.get(0).url);

    assertEquals("[{\"id\":33147,\"name\":\"Refinancing\",\"photos\":"
      + "[{\"name\":\"347.png\",\"url\":\"/loans/568/photos/092\"}],"
      + "\"username\":\"zach1985\"},{\"id\":7693,\"name\":\"Stuff\","
      + "\"photos\":[{\"name\":\"newpic1.png\",\"url\":\"/loans/123446/photos/890\"}],"
      + "\"username\":\"sengaia\"}]", mapper.writeValueAsString(res));

  }
}
Top answer
1 of 3
1

This may help you:

import java.io.IOException;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Test {
    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();

        String json = "[\r\n" + "    {\r\n" + "        \"example\": \"test\",\r\n" + "        \"is_valid\": true\r\n"
                + "    },\r\n" + "    {\r\n" + "        \"example\": \"test2\",\r\n" + "        \"is_valid\": true\r\n"
                + "    }\r\n" + "]";
        Example[] ex = mapper.readValue(json, Example[].class);

    }

}

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({ "example", "is_valid" })
class Example {

    @JsonProperty("example")
    private String example;
    @JsonProperty("is_valid")
    private Boolean isValid;

    public String getExample() {
        return example;
    }

    @JsonProperty("example")
    public void setExample(String example) {
        this.example = example;
    }

    @JsonProperty("is_valid")
    public Boolean getIsValid() {
        return isValid;
    }

    @JsonProperty("is_valid")
    public void setIsValid(Boolean isValid) {
        this.isValid = isValid;
    }
}
2 of 3
1

When response is a JSON Object you can use default bean deserialiser. In case it is a JSON Array you can read it as array and create response object manually. Below you can find example custom deserialiser and BeanDeserializerModifier which is used to register custom deserialiser. BeanDeserializerModifier allows to use default deserialiser when JSON payload fits POJO model:

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.BeanDeserializer;
import com.fasterxml.jackson.databind.deser.BeanDeserializerBase;
import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier;
import com.fasterxml.jackson.databind.exc.MismatchedInputException;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.type.CollectionType;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        SimpleModule module = new SimpleModule();
        module.setDeserializerModifier(new BeanDeserializerModifier() {
            @Override
            public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer<?> deserializer) {
                if (beanDesc.getBeanClass() == Response.class) {
                    return new ResponseJsonDeserializer((BeanDeserializerBase) deserializer);
                }
                return super.modifyDeserializer(config, beanDesc, deserializer);
            }
        });

        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(module);


        System.out.println(mapper.readValue(jsonFile, Response.class));
    }
}

class ResponseJsonDeserializer extends BeanDeserializer {

    private final BeanDeserializerBase baseDeserializer;

    protected ResponseJsonDeserializer(BeanDeserializerBase src) {
        super(src);
        this.baseDeserializer = src;
    }

    @Override
    public Response deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        if (p.currentToken() == JsonToken.START_OBJECT) {
            return (Response) baseDeserializer.deserialize(p, ctxt);
        }
        if (p.currentToken() == JsonToken.START_ARRAY) {
            CollectionType collectionType = ctxt.getTypeFactory().constructCollectionType(List.class, Item.class);
            JsonDeserializer<Object> deserializer = ctxt.findRootValueDeserializer(collectionType);
            List<Item> results = (List<Item>) deserializer.deserialize(p, ctxt);

            Response response = new Response();
            response.setCount(results.size());
            response.setResults(results);

            return response;
        }

        throw MismatchedInputException.from(p, Response.class, "Only object or array!");
    }
}

class Response {

    private int count;
    private List<Item> results;

    // getters, setters, toString
}

class Item {

    private String example;

    @JsonProperty("is_valid")
    private boolean isValid;

    // getters, setters, toString
}

Above code for JSON Object payload prints:

Response{count=5, results=[Item{example='test', isValid=true}, Item{example='test2', isValid=true}]}

And for JSON Array payload prints:

Response{count=2, results=[Item{example='test', isValid=true}, Item{example='test2', isValid=true}]}
🌐
Reddit
reddit.com › r/javahelp › help deserializing a json array of arrays in dsl-json
r/javahelp on Reddit: Help deserializing a JSON array of arrays in DSL-JSON
September 1, 2022 -

I want to deserialize this data:

[[ 1, 1, "Neil Peart", 67, "189 Carlton Street", "M5A 2K7", 21.12 ],
[ 2, 2, "Geddy Lee", 67, "189 Carlton Street", "M5A 2K7", -21.12 ],
[ 3, 3, "Alex Lifeson", 67, "189 Carlton Street", "M5A 2K7", 211.2 ]]

When I use this:

ObjectMapper mapper = new ObjectMapper();
byte[] input = jsonString.getBytes( StandardCharsets.US_ASCII );
com.google.gson.JsonObject dslObject1 = mapper.readValue( jsonString, com.google.gson.JsonObject.class );

It throws a JsonProcessingException with the message:

Cannot deserialize value of type `com.google.gson.JsonObject` from Array value (token `JsonToken.START_ARRAY`)

at [Source: (String)"[[1,1,"Neil Peart",67,"189 Carlton Street","M5A 2K7",21.12]...

When I use this:

byte[] input = jsonString.getBytes( StandardCharsets.US_ASCII );
com.dslplatform.json.JsonObject dslObject2 = dslJson.deserialize( com.dslplatform.json.JsonObject.class, input, input.length );`

it throws an IOException with this message:

Unable to find reader for provided type: interface com.dslplatform.json.JsonObject and fallback serialization is not registered.

Any suggestions?

🌐
W3Docs
w3docs.com › java
How to use Jackson to deserialise an array of objects
Create a Java class that represents the object you want to deserialize. For example: public class User { private int id; private String name; // add getters and setters } Use the ObjectMapper class from the Jackson library to deserialize the JSON array...
Find elsewhere
🌐
How to do in Java
howtodoinjava.com › home › collections framework › java arraylist › serialize and deserialize an arraylist in java (examples)
Serialize and Deserialize an ArrayList in Java (Examples)
3 weeks ago - To serialize an ArrayList in Java, ... to a List. Serialization turns an object into bytes, and deserialization reads the bytes and builds a new object from them....
Top answer
1 of 2
3

Jackson, by default, attempts to deserialize JSON array values into either Java array types or Collection types (eg. ArrayList). But you're trying to make it deserialize a JSON array like [600,200] into a AdDimension object. This won't work out of the box.

You can change your JSON like other answers have suggested or you use a custom deserialization strategy.

Your first option is to define a custom JsonDeserializer (though you should use its sublcass StdDeserializer)

class AdDimensionDeserializer extends JsonDeserializer<AdDimension> {
    @Override
    public AdDimension deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        // you have complete control over the tokens in the JSON, so validate as you wish
        ArrayNode arrayNode = parser.readValueAsTree();
        return new AdDimension(arrayNode.get(0).asInt(), arrayNode.get(1).asInt());
    }
}

and register it as

@JsonDeserialize(using = AdDimensionDeserializer.class)
class AdDimension {

Jackson will instantiate AdDimensionDeserializer and use the instance to deserialize the JSON array elements into an instance(s) of AdDimension.

Another option is to use @JsonCreater

Marker annotation that can be used to define constructors and factory methods as one to use for instantiating new instances of the associated class.

For example

@JsonCreator
public AdDimension(int[] dimensions) {
    // again, validate as required
    this.width = dimensions[0];
    this.height = dimensions[1];
}

Jackson will find this constructor and use it to deserialize your JSON. It will first attempt to deserialize the text [300,250] into a int[], which it obviously can, and then pass that to your constructor.

2 of 2
1

Maybe is a bad json format??

I think it should be like this

[
  {
    "id": 1,
    "targetedCountries": ["CA", "IT"],
    "targetedDomain": "apple.com",
    "adDimensions": [{"width":300, "height":250}, {"width":600, "height":200}]
  }
]

I can´t test it now, but it seems to be no OK.

🌐
Coderanch
coderanch.com › t › 557481 › java › Serialization-Deserialization-Array-Objects
Serialization/Deserialization of an Array of Objects (Java in General forum at Coderanch)
November 1, 2011 - Rob Spoor wrote:If rectCount is the length of the array, I think you mean rectCount - 1. Originally I thought that if you initialized an array to 0 it would work, but I wastold that you need to initalize it to 1 to be the first element 0.
🌐
Rip Tutorial
riptutorial.com › deserialize json collection to collection of objects using jackson
Java Language Tutorial => Deserialize JSON collection to collection...
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.type.CollectionType; ... Failing to do so may lead to loss of generic type argument which will lead to deserialization failure.
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-efficiently-serialize-and-deserialize-arrays-in-java
How to Efficiently Serialize and Deserialize Arrays in Java? - GeeksforGeeks
July 23, 2025 - Deserialize: Reads the array length, creates a new array, and reads each element into the array. ... import java.io.*; // Driver Class public class GFG { // Main Function public static void main(String[] args) { int[] intArray = {10, 20, 30, ...
🌐
Javatpoint
javatpoint.com › deserialize-to-collection-and-array-in-jackson
Deserialize to Collection/Array in Jackson - javatpoint
s JSON Views is another important element of Jackson. JSON Views is also used for serializing and deserializing Java objects. We use @JsonView annotation for customizing the view at the time of serializing/deserializing.
Top answer
1 of 2
135

The example Java data structure in the original question does not match the description of the JSON structure in the comment.

The JSON is described as

"an array of {object with an array of {object}}".

In terms of the types described in the question, the JSON translated into a Java data structure that would match the JSON structure for easy deserialization with Gson is

"an array of {TypeDTO object with an array of {ItemDTO object}}".

But the Java data structure provided in the question is not this. Instead it's

"an array of {TypeDTO object with an array of an array of {ItemDTO object}}".

A two-dimensional array != a single-dimensional array.

This first example demonstrates using Gson to simply deserialize and serialize a JSON structure that is "an array of {object with an array of {object}}".

input.json Contents:

[
  {
    "id":1,
    "name":"name1",
    "items":
    [
      {"id":2,"name":"name2","valid":true},
      {"id":3,"name":"name3","valid":false},
      {"id":4,"name":"name4","valid":true}
    ]
  },
  {
    "id":5,
    "name":"name5",
    "items":
    [
      {"id":6,"name":"name6","valid":true},
      {"id":7,"name":"name7","valid":false}
    ]
  },
  {
    "id":8,
    "name":"name8",
    "items":
    [
      {"id":9,"name":"name9","valid":true},
      {"id":10,"name":"name10","valid":false},
      {"id":11,"name":"name11","valid":false},
      {"id":12,"name":"name12","valid":true}
    ]
  }
]

Foo.java:

import java.io.FileReader;
import java.util.ArrayList;

import com.google.gson.Gson;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
    System.out.println(gson.toJson(myTypes));
  }
}

class TypeDTO
{
  int id;
  String name;
  ArrayList<ItemDTO> items;
}

class ItemDTO
{
  int id;
  String name;
  Boolean valid;
}

This second example uses instead a JSON structure that is actually "an array of {TypeDTO object with an array of an array of {ItemDTO object}}" to match the originally provided Java data structure.

input.json Contents:

[
  {
    "id":1,
    "name":"name1",
    "items":
    [
      [
        {"id":2,"name":"name2","valid":true},
        {"id":3,"name":"name3","valid":false}
      ],
      [
        {"id":4,"name":"name4","valid":true}
      ]
    ]
  },
  {
    "id":5,
    "name":"name5",
    "items":
    [
      [
        {"id":6,"name":"name6","valid":true}
      ],
      [
        {"id":7,"name":"name7","valid":false}
      ]
    ]
  },
  {
    "id":8,
    "name":"name8",
    "items":
    [
      [
        {"id":9,"name":"name9","valid":true},
        {"id":10,"name":"name10","valid":false}
      ],
      [
        {"id":11,"name":"name11","valid":false},
        {"id":12,"name":"name12","valid":true}
      ]
    ]
  }
]

Foo.java:

import java.io.FileReader;
import java.util.ArrayList;

import com.google.gson.Gson;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
    System.out.println(gson.toJson(myTypes));
  }
}

class TypeDTO
{
  int id;
  String name;
  ArrayList<ItemDTO> items[];
}

class ItemDTO
{
  int id;
  String name;
  Boolean valid;
}

Regarding the remaining two questions:

is Gson extremely fast?

Not compared to other deserialization/serialization APIs. Gson has traditionally been amongst the slowest. The current and next releases of Gson reportedly include significant performance improvements, though I haven't looked for the latest performance test data to support those claims.

That said, if Gson is fast enough for your needs, then since it makes JSON deserialization so easy, it probably makes sense to use it. If better performance is required, then Jackson might be a better choice to use. It offers much (maybe even all) of the conveniences of Gson.

Or am I better to stick with what I've got working already?

I wouldn't. I would most always rather have one simple line of code like

TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);

...to easily deserialize into a complex data structure, than the thirty lines of code that would otherwise be needed to map the pieces together one component at a time.

2 of 2
3

Use your bean class like this, if your JSON data starts with an an array object. it helps you.

Users[] bean = gson.fromJson(response,Users[].class);

Users is my bean class.

Response is my JSON data.

🌐
Google Groups
groups.google.com › g › rest-assured › c › a0m6wKzzy6c
Deserializing JSON array of objects into POJO
{ "data": [ { "encodedKey": "12345", "id": "77", "creationDate": "2017-01-23T13:02:56Z", "lastModifiedDate": "2017-01-25T15:54:59Z", "name": "Branch 1", "phoneNumber": "", "emailAddress": "" } ] } and the following object model: public class Branch { @NotNull private String id; @NotNull private String name; @NotNull @Past private Date creationDate; @NotNull private Date lastModifiedDate; private String phoneNumber; @Email private String emailAddress; // getters & setters } My question is if there's a possible solution to serializing/deserializing other than wrapping the Branch into another class (e.g.