How to (completely) deserialize json into a generic List?

后端 未结 2 1846
走了就别回头了
走了就别回头了 2021-01-21 04:45

When using an ObjectMapper to transform a json String into an entity, I can make it generic as:

public  E getConvertedAs(Strin         


        
相关标签:
2条回答
  • 2021-01-21 05:20

    This method can help to read json to an object or collections:

    public class JsonUtil {
        private static final ObjectMapper mapper = new ObjectMapper();
    
        public static <T>T toObject(String json, TypeReference<T> typeRef){
            T t = null;
            try {
                t = mapper.readValue(json, typeRef);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return t;
        }
    }
    

    Read json to list:

    List<Device> devices= JsonUtil.toObject(jsonString,
                                new TypeReference<List<Device>>() {});
    

    Read json to object:

    Device device= JsonUtil.toObject(jsonString,
                                    new TypeReference<Device>() {});
    
    0 讨论(0)
  • 2021-01-21 05:41
    public static <E> List<E> fromJson(String in_string, Class<E> in_type) throws JsonParseException, JsonMappingException, IOException{
        return new ObjectMapper().readValue(in_string, new TypeReference<List<E>>() {});
    }
    

    Compiles on my computer. Note that I haven't tested it, though.

    0 讨论(0)
提交回复
热议问题