pom.xml依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.1</version>
</dependency>
JsonUtils.java 内容:
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
/**
* Created by Bill.Tang on 2018-9-27.
*/
public class JsonUtils {
// 定义jackson对象
private static final ObjectMapper MAPPER = new ObjectMapper();
/**
* 将对象转换成json字符串。
*/
public static String objectToJson(Object data) {
try {
String string = MAPPER.writeValueAsString(data);
return string;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
/**
* 将json结果集转化为对象
*/
public static <T> T jsonToPoJo(String jsonData, Class<T> beanType) {
try {
T t = MAPPER.readValue(jsonData, beanType);
return t;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 将json数据转换成pojo对象list
*/
public static <T> T jsonToList(String jsonData,TypeReference<T> typeReference) {
try {
return MAPPER.readValue(jsonData, typeReference);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
使用例子代码
List<DeviceIdBeanRes> deviceIdBeanResList =
JsonUtils.parseJson("your json", new TypeReference<List<yourclass>>() {
});

本文详细介绍了一种利用Jackson库实现JSON与Java对象相互转换的方法。通过解析pom.xml依赖配置,介绍了如何在项目中引入Jackson库,并展示了JsonUtils类的具体实现,包括将Java对象转换为JSON字符串、将JSON字符串转换为Java对象以及将JSON数据转换为对象列表等功能。最后,通过示例代码演示了如何使用这些方法。
260





