json轉list或物件
阿新 • • 發佈:2019-02-15
/**
* 使用泛型方法,把json字串轉換為相應的JavaBean物件。
* (1)轉換為普通JavaBean:readValue(json,Student.class)
* (2)轉換為List,如List<Student>,將第二個引數傳遞為Student
* [].class.然後使用Arrays.asList();方法把得到的陣列轉換為特定型別的List
*
* @param jsonStr
* @param valueType
* @return
*/
public static <T> T readValue(String jsonStr, Class<T> valueType) {
if (objectMapper == null) {
objectMapper = new ObjectMapper();
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
}
try {
return objectMapper.readValue(jsonStr, valueType);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* json陣列轉List
* @param jsonStr
* @param valueTypeRef
* @return
*/
public static <T> T readValue(String jsonStr, TypeReference<T> valueTypeRef){
if (objectMapper == null) {
objectMapper = new ObjectMapper();
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
}
try {
return objectMapper.readValue(jsonStr, valueTypeRef);
} catch (Exception e) {
e.printStackTrace();
}
return null;
* 使用泛型方法,把json字串轉換為相應的JavaBean物件。
* (1)轉換為普通JavaBean:readValue(json,Student.class)
* (2)轉換為List,如List<Student>,將第二個引數傳遞為Student
* [].class.然後使用Arrays.asList();方法把得到的陣列轉換為特定型別的List
*
* @param jsonStr
* @param valueType
* @return
*/
public static <T> T readValue(String jsonStr, Class<T> valueType) {
if (objectMapper == null) {
objectMapper = new ObjectMapper();
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
}
try {
return objectMapper.readValue(jsonStr, valueType);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* json陣列轉List
* @param jsonStr
* @param valueTypeRef
* @return
*/
public static <T> T readValue(String jsonStr, TypeReference<T> valueTypeRef){
if (objectMapper == null) {
objectMapper = new ObjectMapper();
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
}
try {
return objectMapper.readValue(jsonStr, valueTypeRef);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@SuppressWarnings("unused")
@Post("/test")
public String test(Invocation inv,
@NotBlankCheckRequired @Param("json") String json,
@NotBlankCheckRequired @Param("jsonArray") String jsonArray){
SysUser user = JacksonUtil.readValue(json, SysUser.class);
SysUser userList1 = JacksonUtil.readValue(json, new TypeReference<SysUser>() {});
List<SysUser> userList = JacksonUtil.readValue(jsonArray, new TypeReference<List<SysUser>>() {});
return "@" + CommonsUtil.returnObjectToJson(ResponseObject.newSuccessResponseObject(""));
}
$('#test11').live('click', function () { var array = []; var params = { username: 'wpf', password: '1234', id: '124234' }; array.push(params); reportInfoController.test({json: JSON.stringify(params), jsonArray:JSON.stringify(array)},function(data){ if(data.status==200){ common.layer.success("儲存成功!",function(){ }); } }); });