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

后端 未结 2 1847
走了就别回头了
走了就别回头了 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 toObject(String json, TypeReference typeRef){
            T t = null;
            try {
                t = mapper.readValue(json, typeRef);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return t;
        }
    }
    

    Read json to list:

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

    Read json to object:

    Device device= JsonUtil.toObject(jsonString,
                                    new TypeReference() {});
    

提交回复
热议问题