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 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() {});