When using an ObjectMapper
to transform a json String
into an entity, I can make it generic as:
public E getConvertedAs(Strin
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>() {});
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.