public static String toJson(Object obj) {
ObjectMapper om = new ObjectMapper();
om.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, Boolean.FALSE);
// 忽略新增未知 回傳參數
om.setSerializationInclusion(Inclusion.NON_NULL);
try {
return om.writeValueAsString(obj);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
return null;
}
public static <T> T fromJson(String src, Class<T> t) {
ObjectMapper om = new ObjectMapper();
om.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, Boolean.FALSE);
// 忽略新增未知 回傳參數
try {
return ((T) om.readValue(src, t));
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
return null;
}
沒有留言:
張貼留言