978

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 this:

//json input
{
    "id" : "junk",
    "stuff" : "things"
}

//Java
MyClass instance = objectMapper.readValue(json, MyClass.class);

Now for an array I want to do this:

//json input
[{
    "id" : "junk",
    "stuff" : "things"
},
{
    "id" : "spam",
    "stuff" : "eggs"
}]

//Java
List<MyClass> entries = ?

Anyone know if there is a magic missing command? If not then what is the solution?

JJD
  • 47,369
  • 53
  • 194
  • 328
Ollie Edwards
  • 13,140
  • 6
  • 27
  • 34
  • 2
    I prefer Google's GSON library for dealing with JSON. It is worth checking out if you haven't tryed it yet... makes working with it very easy and intuitive. – Jesse Webb Jun 14 '11 at 20:51
  • 12
    FWIW The possible solutions to this specific problem with Gson are almost identical to what's possible with Jackson's Data Binding API. – Programmer Bruce Jun 14 '11 at 21:01
  • 21
    Gweebz -- maybe you would like to explain why you feel GSON is a better choice (compared to Jackson)? – StaxMan Jun 15 '11 at 17:28

9 Answers9

2075

First create a mapper :

import com.fasterxml.jackson.databind.ObjectMapper;// in play 2.3
ObjectMapper mapper = new ObjectMapper();

As Array:

MyClass[] myObjects = mapper.readValue(json, MyClass[].class);

As List:

List<MyClass> myObjects = mapper.readValue(jsonInput, new TypeReference<List<MyClass>>(){});

Another way to specify the List type:

List<MyClass> myObjects = mapper.readValue(jsonInput, mapper.getTypeFactory().constructCollectionType(List.class, MyClass.class));
Moebius
  • 5,662
  • 5
  • 38
  • 53
Programmer Bruce
  • 61,617
  • 6
  • 98
  • 96
  • 53
    One extra note, if while parsing you get an error such as `JsonMappingException: No suitable constructor found for type` then it means you need to added a default constructor to your class adding a private no-arg constructor fixed it for me. – SyntaxRules Aug 09 '13 at 16:07
  • 12
    @SyntaxRules adding explicit constructor is necessary if you have an explicit constructor -- if not, compiler automatically creates public "empty" constructor. Good point. Another common problem is that inner classes need to be `static` -- otherwise they never have zero-arg constructor. – StaxMan Aug 20 '13 at 00:09
  • 310
    Btw, `List myObjects = Arrays.asList(mapper.readValue(json, MyClass[].class))` works up to 10 time faster than TypeRefence. –  Jun 05 '14 at 12:44
  • 6
    I'm looking for a generic type version. – Stephane Sep 01 '14 at 13:54
  • 1
    @EugeneTskhovrebov your way is the cleanest for inlining. The others require casting or declaring. I suggest adding it as its own answer to help highlight it, and give you some rep. – Erik B Dec 06 '14 at 19:02
  • Any reason why mapper.readValues() -> Iterator is not working? – aldo.roman.nurena May 02 '15 at 16:12
  • @Programmer Bruce - I want to read and assign the yaml to our properties `properties = mapper.readValue(content, Properties.class);` is it possible to pass an object to the readValue instead of string ? – Suleman khan Jan 19 '16 at 15:28
  • For more information maybe checkout this article I found: http://www.mkyong.com/java/jackson-2-convert-java-object-to-from-json/ – Eruvanos Jun 09 '16 at 13:17
  • How to achieve the above deserialisation if it coming with a root wrapped: {"root": ["string1","strng2"]} ??? Here root is a custom name ( can be anything). – Siddharth Trikha Aug 19 '16 at 07:24
  • how can I use @EugeneTskhovrebov answer If I have a `Class clazz`. Passing `T[].class` no compily. – hvgotcodes Dec 03 '16 at 01:35
  • 1
    I'd like to know how to do the same but with a nested array like so: `{ "data": [ {...}, {...}, {...} ] }` I've spent a couple of hours now trying to figure out how to apply this to my situation. – Maninacan Jan 27 '17 at 17:11
  • 3
    In response to my own comment above, first parse the json string to a jsonNode and then access the property of the array like this: ```JsonNode jsonNode = MAPPER.readTree(json); String arrayString = jsonNode.get("data").toString();``` Then follow @Programmer Bruce's instructions above. ```List sources = MAPPER.readValue(arrayString, new TypeReference>() {});``` – Maninacan Jan 27 '17 at 17:57
  • 1
    @Stephane I have declared the next method to get the generic class: `private Class getObjectClass() { return (Class)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0]; }` then I use it like this: `List systemProperties = MAPPER.readValue(columnString, MAPPER.getTypeFactory().constructCollectionType(List.class, getObjectClass()));` – Aebsubis Mar 03 '17 at 17:02
  • I am receiving a compile time error: `readValue(com.fasterxml.jackson.databind.JsonNode, com.fasterxml.jackson.databind.type.CollectionType)` – Adam Hurwitz Jun 13 '17 at 19:22
  • This does not work if MyClass.class was String.class. Any idea why? – Righto Mar 12 '18 at 12:57
  • 1
    @SyntaxRules you should add this as an additional Answer as this helped me with my case. – Snickbrack Jan 04 '19 at 12:15
  • What if my json array is embedded in an object that I want to deserialize? How can I annotate my List object so that the conversion will be done automatically? – John Douma Mar 12 '20 at 15:37
  • It's very difficult to `mock` `TypeReference`, so using array notation. – Mehraj Malik Aug 31 '21 at 05:46
  • The last option did what I needed. – scarface Nov 16 '21 at 13:00
248

From Eugene Tskhovrebov

List<MyClass> myObjects = Arrays.asList(mapper.readValue(json, MyClass[].class))

This solution seems to be the best for me.

Marthym
  • 2,799
  • 2
  • 13
  • 22
  • For those working with Agents in Java, Lotus Domino, this is the way to go. I tried some of the other solutions, but always got a `ResourceNotFoundException` – John Mar 08 '17 at 14:38
  • 1
    SyntaxRules addition in the comments for the answer above may be required for this solution as we, it was for me. I just wanted to add that so that it is not lost. – Rob Apr 19 '17 at 09:04
  • 2
    or `Arrays.asList(Json.fromJson(json.get("fieldName"), MyClass[].class))` – Al-Mothafar Sep 14 '17 at 07:07
  • 3
    or `List myObjects = Arrays.asList(mapper.treeToValue(jsonNode.get("fieldName"), MyClass[].class))` – Collin Krawll Mar 03 '18 at 23:56
  • @CollinKrawll what does objectmapper.treetovalue do? – Eswar Sep 20 '18 at 09:39
  • It's a convenience method that loops all nodes under "fieldName", deserializes each one into an instance of MyClass and returns them all as an array (`MyClass[]`). We are then using the `Arrays.asList` function to convert the array (`MyClass[]`) into a List (`List`) . Here's a link to the [docs](https://fasterxml.github.io/jackson-databind/javadoc/2.8/com/fasterxml/jackson/databind/ObjectMapper.html#treeToValue(com.fasterxml.jackson.core.TreeNode,%20java.lang.Class)) – Collin Krawll Sep 28 '18 at 23:28
  • This is an excellent solution for the simple case of a root json array! – Brian Knoblauch Mar 28 '19 at 17:37
55

For Generic Implementation:

public static <T> List<T> parseJsonArray(String json,
                                         Class<T> classOnWhichArrayIsDefined) 
                                         throws IOException, ClassNotFoundException {
   ObjectMapper mapper = new ObjectMapper();
   Class<T[]> arrayClass = (Class<T[]>) Class.forName("[L" + classOnWhichArrayIsDefined.getName() + ";");
   T[] objects = mapper.readValue(json, arrayClass);
   return Arrays.asList(objects);
}
Pallav Jha
  • 3,069
  • 2
  • 28
  • 48
16

First create an instance of ObjectReader which is thread-safe.

ObjectMapper objectMapper = new ObjectMapper();
ObjectReader objectReader = objectMapper.reader().forType(new TypeReference<List<MyClass>>(){});

Then use it :

List<MyClass> result = objectReader.readValue(inputStream);
Greg D
  • 181
  • 1
  • 3
  • 1
    we do get - com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token at [Source: java.io.FileInputStream@33fec21; line: 1, column: 1] – Dinesh Kumar Jan 07 '20 at 16:12
  • That can be overcome by adding this extra layer of configuration to our ObjectMapper() instance: mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); – javiergarval Jan 12 '22 at 16:38
  • do not work with error Can not deserialize instance of java.util.ArrayList out of START_OBJECT token at – Whu_Kingsun Jan 24 '22 at 10:58
11

try this

List<MyClass> list = mapper.readerForListOf(MyClass.class).readValue(json)
hantian_pang
  • 529
  • 5
  • 8
8
try {
    ObjectMapper mapper = new ObjectMapper();
    JsonFactory f = new JsonFactory();
    List<User> lstUser = null;
    JsonParser jp = f.createJsonParser(new File("C:\\maven\\user.json"));
    TypeReference<List<User>> tRef = new TypeReference<List<User>>() {};
    lstUser = mapper.readValue(jp, tRef);
    for (User user : lstUser) {
        System.out.println(user.toString());
    }

} catch (JsonGenerationException e) {
    e.printStackTrace();
} catch (JsonMappingException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
Alessandro Da Rugna
  • 4,491
  • 20
  • 39
  • 62
jerome
  • 99
  • 1
  • 1
8

I was unable to use this answer because my linter won't allow unchecked casts.

Here is an alternative you can use. I feel it is actually a cleaner solution.

public <T> List<T> parseJsonArray(String json, Class<T> clazz) throws JsonProcessingException {
  var tree = objectMapper.readTree(json);
  var list = new ArrayList<T>();
  for (JsonNode jsonNode : tree) {
    list.add(objectMapper.treeToValue(jsonNode, clazz));
  }
  return list;
}
lbenedetto
  • 1,830
  • 17
  • 37
6

here is an utility which is up to transform json2object or Object2json, whatever your pojo (entity T)

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

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

/**
 * 
 * @author TIAGO.MEDICI
 * 
 */
public class JsonUtils {

    public static boolean isJSONValid(String jsonInString) {
        try {
            final ObjectMapper mapper = new ObjectMapper();
            mapper.readTree(jsonInString);
            return true;
        } catch (IOException e) {
            return false;
        }
    }

    public static String serializeAsJsonString(Object object) throws JsonGenerationException, JsonMappingException, IOException {
        ObjectMapper objMapper = new ObjectMapper();
        objMapper.enable(SerializationFeature.INDENT_OUTPUT);
        objMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        StringWriter sw = new StringWriter();
        objMapper.writeValue(sw, object);
        return sw.toString();
    }

    public static String serializeAsJsonString(Object object, boolean indent) throws JsonGenerationException, JsonMappingException, IOException {
        ObjectMapper objMapper = new ObjectMapper();
        if (indent == true) {
            objMapper.enable(SerializationFeature.INDENT_OUTPUT);
            objMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        }

        StringWriter stringWriter = new StringWriter();
        objMapper.writeValue(stringWriter, object);
        return stringWriter.toString();
    }

    public static <T> T jsonStringToObject(String content, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
        T obj = null;
        ObjectMapper objMapper = new ObjectMapper();
        obj = objMapper.readValue(content, clazz);
        return obj;
    }

    @SuppressWarnings("rawtypes")
    public static <T> T jsonStringToObjectArray(String content) throws JsonParseException, JsonMappingException, IOException {
        T obj = null;
        ObjectMapper mapper = new ObjectMapper();
        obj = mapper.readValue(content, new TypeReference<List>() {
        });
        return obj;
    }

    public static <T> T jsonStringToObjectArray(String content, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
        T obj = null;
        ObjectMapper mapper = new ObjectMapper();
        mapper = new ObjectMapper().configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
        obj = mapper.readValue(content, mapper.getTypeFactory().constructCollectionType(List.class, clazz));
        return obj;
    }
Tiago Medici
  • 1,514
  • 18
  • 17
-1

you could also create a class which extends ArrayList:

public static class MyList extends ArrayList<Myclass> {}

and then use it like:

List<MyClass> list = objectMapper.readValue(json, MyList.class);
pero_hero
  • 2,652
  • 2
  • 8
  • 19