How to use Jackson to deserialise an array of objects

前端 未结 8 1303
梦谈多话
梦谈多话 2020-11-21 22:58

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.

相关标签:
8条回答
  • 2020-11-21 23:04

    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);
    
    0 讨论(0)
  • 2020-11-21 23:08

    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));
    
    0 讨论(0)
  • 2020-11-21 23:16
    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();
    }
    
    0 讨论(0)
  • 2020-11-21 23:20

    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;
    }
    
    0 讨论(0)
  • 2020-11-21 23:21

    From Eugene Tskhovrebov

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

    This solution seems to be the best for me

    0 讨论(0)
  • 2020-11-21 23:21

    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);
    
    0 讨论(0)
提交回复
热议问题