0
0

More than 1 year has passed since last update.

JacksonでJSONとListを相互変換する

Posted at

JSON文字列をListに変換する

public static <T> List<T> convertToList(String json, Class<T> clazz) {
    List<T> list = null;
    if (!StringUtils.isEmpty(json)) {
        ObjectMapper mapper = new ObjectMapper();
        final CollectionType jt = mapper.getTypeFactory().constructCollectionType(List.class, clazz);
        try {
            list = mapper.readValue(json, jt);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
    return list;
}

ListをJSON文字列に変換する

public static <T> String convertToJson(List<T> list) {
    ObjectMapper mapper = new ObjectMapper();
    String json = "";
    if (Objects.nonNull(list)) {
        try {
            json = mapper.writeValueAsString(list);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return json;
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0