Can you build the array as an object before writing it, rather than bothering with all the individual pieces?

CopyObjectMapper mapper = new ObjectMapper();
ArrayNode array = mapper.createArrayNode();

int i = 0;
while (i < 6) {
    array.add(mapper.createArrayNode().add("" + i++).add("" + i++));
}
System.out.println(array);

Results in:

Copy[["0","1"],["2","3"],["4","5"]]

If you're not dealing with several megabytes of data or very tight memory constraints, this might turn out to be more maintainable as well.

Answer from Chris on Stack Overflow
🌐
Baeldung
baeldung.com › home › json › jackson › jackson – unmarshall to collection/array
Jackson - Unmarshall to Collection/Array | Baeldung
April 26, 2024 - Jackson can easily deserialize to a Java Array: @Test public void givenJsonArray_whenDeserializingAsArray_thenCorrect() throws JsonParseException, JsonMappingException, IOException { ObjectMapper mapper = new ObjectMapper(); List<MyDto> listOfDtos = Lists.newArrayList( new MyDto("a", 1, true), new MyDto("bc", 3, false)); String jsonArray = mapper.writeValueAsString(listOfDtos); // [{"stringValue":"a","intValue":1,"booleanValue":true}, // {"stringValue":"bc","intValue":3,"booleanValue":false}] MyDto[] asArray = mapper.readValue(jsonArray, MyDto[].class); assertThat(asArray[0], instanceOf(MyDto.
Discussions

java - How to parse a JSON string to an array using Jackson - Stack Overflow
Which is the simplest way to do it using Jackson ObjectMapper? ... I had a similar situation , but decided to de-serialise to JSONArray object instead of doing it to a class, since it would avoid class serialisation issues in future. More on stackoverflow.com
🌐 stackoverflow.com
How to parse Json array with 2 or more different types using Jackson?

http://www.baeldung.com/jackson-inheritance

You'll need to have those types inherit from one base class though.

Also; that is really bad JSON.

More on reddit.com
🌐 r/javahelp
11
4
September 18, 2016
java - Jackson how to transform JsonNode to ArrayNode without casting? - Stack Overflow
I am changing my JSON library from org.json to Jackson and I want to migrate the following code: JSONObject datasets = readJSON(new URL(DATASETS)); JSONArray datasetArray = datasets.getJSONArray(" More on stackoverflow.com
🌐 stackoverflow.com
(JAVA) JsonPath.read() / Jackson JSONArray messing up JSON format
Link isn’t working. More on reddit.com
🌐 r/learnprogramming
2
1
March 22, 2022
🌐
Attacomsian
attacomsian.com › blog › jackson-create-json-array
How to create a JSON array using Jackson
October 14, 2022 - A short tutorial to learn how to create a JSON array using Jackson API.
🌐
Mkyong
mkyong.com › home › java › how to parse json array with jackson
How to parse JSON Array with Jackson - Mkyong.com
April 23, 2024 - convert JSON array to Array objects Person[] person1 = mapper.readValue(jsonArray, Person[].class); for (Person p : person1) { System.out.println(p); } // 2. convert JSON array to List List<Person> person2 = mapper.readValue(jsonArray, new TypeReference<>() { }); person2.forEach(System.out::println); } } ... Person{name='mkyong', age=42} Person{name='ah pig', age=20} Person{name='mkyong', age=42} Person{name='ah pig', age=20} ... package com.mkyong.json.jackson; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.mkyong.json
🌐
Makeseleniumeasy
makeseleniumeasy.com › 2020 › 05 › 16 › rest-assured-tutorial-27-how-to-create-json-array-using-jackson-api-objectmapper-createarraynode
REST Assured Tutorial 27 – How To Create JSON Array Using Jackson API – ObjectMapper – CreateArrayNode()
String jsonArrayAsString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(parentArray); System.out.println("Created Json Array is : "); System.out.println(jsonArrayAsString); That’s all. We have created a JSON Array successfully using Jackson API.
🌐
Stack Abuse
stackabuse.com › converting-json-array-to-a-java-array-or-list
Convert JSON Array to a Java Array or List with Jackson
September 8, 2020 - In this article, we'll convert a JSON array into a Java Array and Java List using Jackson.
🌐
Medium
medium.com › @salvipriya97 › how-to-convert-json-array-to-java-pojo-using-jackson-367ac93f7b15
How to convert JSON array to Java POJO using Jackson | by Priya Salvi | Medium
June 18, 2024 - import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.List; public class Main { public static void main(String[] args) { String jsonArray = "[{\"name\":\"John\", \"age\":30, \"address\":[{\"apartment\":\"A1\",\"street\":\"Main St\",\"pinCode\":\"12345\"}], \"unknownField\":\"value\"}, {\"name\":\"Alice\", \"age\":25, \"address\":[{\"apartment\":\"B2\",\"street\":\"Second St\",\"pinCode\":\"67890\"}]}]"; try { ObjectMapper objectMapper = new ObjectMapper(); List<Person> personList = objectMapper.readValue(jsonArray, new TypeRe
Find elsewhere
🌐
Java Code Geeks
javacodegeeks.com › home › enterprise java
Simplified Json Array Operations with JsonNode in Jackson
May 6, 2024 - When working with JSON arrays ([]), the ArrayNode class in Jackson is especially useful for handling Simplified Array Operations on JsonNode in Jackson, enabling efficient manipulation and traversal of JSON arrays within Java applications.
🌐
TutorialsPoint
tutorialspoint.com › how-to-convert-a-list-to-json-array-using-the-jackson-library-in-java
How to convert a List to JSON array using the Jackson library in Java?
April 29, 2025 - import java.util.*; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.node.ArrayNode; public class ListToJSONArrayUsingArrayNode { public static void main(String[] args) { List < String > list = Arrays.asList("JAVA", "PYTHON", "SCALA", ".NET", "TESTING"); ObjectMapper objectMapper = new ObjectMapper(); ArrayNode arrayNode = objectMapper.createArrayNode(); for (String item: list) { arrayNode.add(item); // adding each item manually } try { String jsonArray = objectMapper.writeValueAsString(arrayNode); System.out.println(jsonArray); } catch (Exception e) { e.printStackTrace(); } } }
🌐
Jenkov
jenkov.com › tutorials › java-json › jackson-objectmapper.html
Jackson ObjectMapper
The Jackson ObjectMapper can also read an array of objects from a JSON array string. Here is an example of reading an object array from a JSON array string: String jsonArray = "[{\"brand\":\"ford\"}, {\"brand\":\"Fiat\"}]"; ObjectMapper objectMapper ...
🌐
Reddit
reddit.com › r/javahelp › how to parse json array with 2 or more different types using jackson?
r/javahelp on Reddit: How to parse Json array with 2 or more different types using Jackson?
September 18, 2016 -

Hi guys, I've been searching online and stackoverflow but can't seem to find an answer to this. Basically the API i'm calling returns a json array as the root object. The two objects inside this array are different types. I have defined two Java classes to represent these two types and I'm wanting to read the json and convert them into my java object with jackson. Seems like there isn't a way to do this??

simple example of my objects:

class Type1 {
  String name
}

class Type2 {
  long age
}

The json coming from the api looks like this:

[
 {
    "name" : "mickey"
  },
  {
    "age" : 100
  }
]

How can I tell jackson to read in this "tree" but convert it to some object that is holding these two?

EDIT Here is a reply I made to another comment:

Ok, it seems like nobody is understanding what I'm saying. For one, I don't have control of the api I'm calling. I get what I get and have to deal with it.

What that api returns is a json ARRAY as the ROOT object. There are two objects in that array. Those two objects are NOT the same types.

IF that array was holding objects of the same type, i could do this:

MyObjects[] myobjs = new Objectmapper().readValue("some json array here", MyObjects[].class);

But like I said, i can't do this. Because the array is not holding objects of the same type. It would be more akin to a tuple like in python.

🌐
Medium
medium.com › @Mohd_Aamir_17 › mastering-json-in-java-a-comprehensive-guide-to-handling-json-objects-arrays-and-nodes-with-df57bf0ebff1
Mastering JSON in Java: A Comprehensive Guide to Handling JSON Objects, Arrays, and Nodes with Jackson | by Mohd Aamir | Medium
November 4, 2024 - Jackson’s ArrayNode class, which extends JsonNode, is specifically for handling JSON arrays. String jsonArrayString = "[{\"id\": 1, \"name\": \"John\"}, {\"id\": 2, \"name\": \"Jane\"}]"; ArrayNode jsonArray = (ArrayNode) objectMapper.rea...
🌐
Reddit
reddit.com › r/learnprogramming › (java) jsonpath.read() / jackson jsonarray messing up json format
r/learnprogramming on Reddit: (JAVA) JsonPath.read() / Jackson JSONArray messing up JSON format
March 22, 2022 -

Just started using this and not finding any answers online, but I'm web-scraping and the method I am using is messing up the format so I can't deserialize to an object when I use the JSON path "$..itemsV2[*]" . It takes the quotes away from the key-value pairs and changes ':' to '=', which is giving me the following error:

Exception in thread "main" com.fasterxml.jackson.core.JsonParseException: Unrecognized token '\_\_typename': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')

When I use "$..itemsV2" then it leaves the original format alone and serializes just fine, but it only returns the first item in the JSON Array. Any ideas?

link: https://pastebin.com/uQ4Dkpmh

The link should work now

SOLVED: turns out ObjectMapper has a super handy method

WmProduct[] wmProducts = objectMapper.convertValue(jsonItemArray,WmProduct[].class);
🌐
Twilio
twilio.com › blog › java-json-with-jackson
Three ways to use Jackson for JSON in Java
July 5, 2020 - Jackson allows you to read JSON into a tree model: Java objects that represent JSON objects, arrays and values. These objects are called things like JsonNode or JsonArray and are provided by Jackson.
🌐
How to do in Java
howtodoinjava.com › home › convert json array to list: gson, jackson and org.json
Convert JSON Array to List: Gson, Jackson and Org.json
September 25, 2023 - When we use Jackson to parse JSON data into Java objects or lists, we should know the target type when dealing with generic types like List<T> or Map<K, V>. The TypeReference class provides the necessary type information to Jackson at runtime ...
🌐
Attacomsian
attacomsian.com › blog › jackson-convert-json-array-to-from-java-list
Convert JSON array to a list using Jackson in Java
November 6, 2022 - In this short tutorial, you'll learn how to use the Jackson library to convert a JSON array string into a list of Java Objects and vice versa.
Top answer
1 of 5
98

The problem is not in your code but in your json:

{"Compemployes":[{"id":1001,"name":"jhon"}, {"id":1002,"name":"jhon"}]}

this represents an object which contains a property Compemployes which is a list of Employee. In that case you should create that object like:

class EmployeList{
    private List<Employe> compemployes;
    (with getter an setter)
}

and to deserialize the json simply do:

EmployeList employeList = mapper.readValue(jsonString,EmployeList.class);

If your json should directly represent a list of employees it should look like:

[{"id":1001,"name":"jhon"}, {"id":1002,"name":"jhon"}]

Last remark:

List<Employee> list2 = mapper.readValue(jsonString, 
TypeFactory.collectionType(List.class, Employee.class));

TypeFactory.collectionType is deprecated you should now use something like:

List<Employee> list = mapper.readValue(jsonString,
TypeFactory.defaultInstance().constructCollectionType(List.class,  
   Employee.class));
2 of 5
1
/*
 It has been answered in http://stackoverflow.com/questions/15609306/convert-string-to-json-array/33292260#33292260
 * put string into file jsonFileArr.json
 * [{"username":"Hello","email":"[email protected]","credits"
 * :"100","twitter_username":""},
 * {"username":"Goodbye","email":"[email protected]"
 * ,"credits":"0","twitter_username":""},
 * {"username":"mlsilva","email":"[email protected]"
 * ,"credits":"524","twitter_username":""},
 * {"username":"fsouza","email":"[email protected]"
 * ,"credits":"1052","twitter_username":""}]
 */

public class TestaGsonLista {

public static void main(String[] args) {
Gson gson = new Gson();
 try {
    BufferedReader br = new BufferedReader(new FileReader(
            "C:\\Temp\\jsonFileArr.json"));
    JsonArray jsonArray = new JsonParser().parse(br).getAsJsonArray();
    for (int i = 0; i < jsonArray.size(); i++) {
        JsonElement str = jsonArray.get(i);
        Usuario obj = gson.fromJson(str, Usuario.class);
        //use the add method from the list and returns it.
        System.out.println(obj);
        System.out.println(str);
        System.out.println("-------");
    }
 } catch (IOException e) {
    e.printStackTrace();
 }
}