当前位置:网站首页>Jackson
Jackson
2022-04-22 04:57:00 【Zhenxiang】
Jackson brief introduction
Jackson It's a simple one based on Java Application Library ,Jackson You can simply Java Object conversion to Json Objects and xml file , It is also possible to Json、xml convert to Java Object's .Jackson The dependent Jar Relatively few packages , Simple and easy to use , And the performance is relatively higher , also Jackson Our community is active , The update speed is also relatively fast .
Jackson Characteristics
- Easy to use -Jackson Of API Provides a high-level look , To simplify common use cases .
- No need to create a map -API Provides default mapping for most object serialization .
- High performance - Fast , Low memory usage , Suitable for large object diagrams or systems .
- clean JSON - Jackson Create a clean and compact JSON result , It's easy to read .
- Do not rely on - The library doesn't need any other library , except JDK.
- Open source code - Jackson It's open source. , Free to use .
Jackson annotation
Jackson The class library contains a lot of annotations , It allows us to quickly build Java Class and JSON The relationship between .
@JsonProperty
@JsonProperty The annotation specifies an attribute for JSON mapping , Mapped by default JSON Property has the same property name as the annotation , However, you can use the value Value modification JSON Property name , There's another one in the note index Property specifies the build JSON The order of attributes , If necessary .
@JsonIgnore
@JsonIgnore Annotations are used to exclude an attribute , So that the attribute is not Jackson Serialization and deserialization .
@JsonIgnoreProperties
@JsonIgnoreProperties Annotations are class annotations . After serializing to JSON When ,@JsonIgnoreProperties({“prop1”, “prop2”}) Will ignore pro1 and pro2 Two attributes . In from JSON Deserialize to Java Class time ,@JsonIgnoreProperties(ignoreUnknown=true) Will ignore everything that doesn't Getter and Setter Properties of . The note is in the Java Classes and JSON It's useful when you don't exactly match .
@JsonIgnoreType
@JsonIgnoreType It's also a class annotation , All properties of the specified type are excluded .
@JsonPropertyOrder
@JsonPropertyOrder and @JsonProperty Of index Properties are similar to , Specifies the order in which properties are serialized .
@JsonRootName
@JsonRootName Comments are used to specify JSON The name of the root property .
Jackson Use
Object serialization and deserialization
/** * json Transfer object * @throws IOException */
public static User json2Pojo() throws IOException {
// establish ObjectMapper The core
ObjectMapper mapper=new ObjectMapper();
// Parse string
String jsonString = "{\"id\":1,\"username\":\"zhansan \",\"password\":\"123456\",\"name\":\"James\"}";
// Deserialize to object json turn Java object
User user = mapper.readValue(jsonString, User.class);
System.out.println(user);
return user;
}
/** * Object turn Json * @throws JsonProcessingException */
public static void pojo2Json() throws IOException {
// establish ObjectMapper The core
ObjectMapper mapper=new ObjectMapper();
String json = mapper.writeValueAsString(json2Pojo());
System.out.println(json);
}
Serialization and deserialization of collections
public class JsonTester {
public static void main(String[] args) {
// establish ObjectMapper object
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"draw\":1,\"recordsTotal\":1,\"recordsFiltered\":1,\"data\":[{\"id\":33,\"title\":\"ad1\",\"subTitle\":\"ad1\",\"titleDesc\":\"ad1\",\"url\":\"https://sale.jd.com/act/XkCzhoisOMSW.html\",\"pic\":\"https://m.360buyimg.com/babel/jfs/t20164/187/1771326168/92964/b42fade7/5b359ab2N93be3a65.jpg\",\"pic2\":\"\",\"content\":\"<p><br></p>\"}],\"error\":null}";
try {
// Deserialization JSON To tree
JsonNode jsonNode = mapper.readTree(jsonString);
// Read from tree data node
JsonNode jsonData = jsonNode.findPath("data");
System.out.println(jsonData);
// Deserialization JSON To the assembly
JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, TbContent.class);
List<TbContent> tbContents = mapper.readValue(jsonData.toString(), javaType);
for (TbContent tbContent : tbContents) {
System.out.println(tbContent);
}
// Serialize the collection to JSON
String json = mapper.writeValueAsString(tbContents);
System.out.println(json);
} catch (IOException e) {
e.printStackTrace();
}
}
}
class TbContent {
private Long id;
private String title;
private String subTitle;
private String titleDesc;
private String url;
private String pic;
private String pic2;
private String content;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSubTitle() {
return subTitle;
}
public void setSubTitle(String subTitle) {
this.subTitle = subTitle;
}
public String getTitleDesc() {
return titleDesc;
}
public void setTitleDesc(String titleDesc) {
this.titleDesc = titleDesc;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
public String getPic2() {
return pic2;
}
public void setPic2(String pic2) {
this.pic2 = pic2;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "TbContent{" +
"id=" + id +
", title='" + title + '\'' +
", subTitle='" + subTitle + '\'' +
", titleDesc='" + titleDesc + '\'' +
", url='" + url + '\'' +
", pic='" + pic + '\'' +
", pic2='" + pic2 + '\'' +
", content='" + content + '\'' +
'}';
}
}
Common methods and tools
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** * Jackson Tool class * <p>Title: MapperUtils</p> * <p>Description: </p> */
public class MapperUtils {
private final static ObjectMapper objectMapper = new ObjectMapper();
public static ObjectMapper getInstance() {
return objectMapper;
}
/** * Convert to JSON character string * * @param obj * @return * @throws Exception */
public static String obj2json(Object obj) throws Exception {
return objectMapper.writeValueAsString(obj);
}
/** * Convert to JSON character string , Ignore the null value * * @param obj * @return * @throws Exception */
public static String obj2jsonIgnoreNull(Object obj) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return mapper.writeValueAsString(obj);
}
/** * Convert to JavaBean * * @param jsonString * @param clazz * @return * @throws Exception */
public static <T> T json2pojo(String jsonString, Class<T> clazz) throws Exception {
objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
return objectMapper.readValue(jsonString, clazz);
}
/** * String conversion to Map<String, Object> * * @param jsonString * @return * @throws Exception */
public static <T> Map<String, Object> json2map(String jsonString) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return mapper.readValue(jsonString, Map.class);
}
/** * String conversion to Map<String, T> */
public static <T> Map<String, T> json2map(String jsonString, Class<T> clazz) throws Exception {
Map<String, Map<String, Object>> map = objectMapper.readValue(jsonString, new TypeReference<Map<String, T>>() {
});
Map<String, T> result = new HashMap<String, T>();
for (Map.Entry<String, Map<String, Object>> entry : map.entrySet()) {
result.put(entry.getKey(), map2pojo(entry.getValue(), clazz));
}
return result;
}
/** * Depth conversion JSON become Map * * @param json * @return */
public static Map<String, Object> json2mapDeeply(String json) throws Exception {
return json2MapRecursion(json, objectMapper);
}
/** * hold JSON It can be interpreted as List, If List Internal elements exist jsonString, Continue to parse * * @param json * @param mapper Parsing tool * @return * @throws Exception */
private static List<Object> json2ListRecursion(String json, ObjectMapper mapper) throws Exception {
if (json == null) {
return null;
}
List<Object> list = mapper.readValue(json, List.class);
for (Object obj : list) {
if (obj != null && obj instanceof String) {
String str = (String) obj;
if (str.startsWith("[")) {
obj = json2ListRecursion(str, mapper);
} else if (obj.toString().startsWith("{")) {
obj = json2MapRecursion(str, mapper);
}
}
}
return list;
}
/** * hold JSON It can be interpreted as Map, If Map Inside Value There is jsonString, Continue to parse * * @param json * @param mapper * @return * @throws Exception */
private static Map<String, Object> json2MapRecursion(String json, ObjectMapper mapper) throws Exception {
if (json == null) {
return null;
}
Map<String, Object> map = mapper.readValue(json, Map.class);
for (Map.Entry<String, Object> entry : map.entrySet()) {
Object obj = entry.getValue();
if (obj != null && obj instanceof String) {
String str = ((String) obj);
if (str.startsWith("[")) {
List<?> list = json2ListRecursion(str, mapper);
map.put(entry.getKey(), list);
} else if (str.startsWith("{")) {
Map<String, Object> mapRecursion = json2MapRecursion(str, mapper);
map.put(entry.getKey(), mapRecursion);
}
}
}
return map;
}
/** * take JSON Array to set * * @param jsonArrayStr * @param clazz * @return * @throws Exception */
public static <T> List<T> json2list(String jsonArrayStr, Class<T> clazz) throws Exception {
JavaType javaType = getCollectionType(ArrayList.class, clazz);
List<T> list = (List<T>) objectMapper.readValue(jsonArrayStr, javaType);
return list;
}
/** * Get generic Collection Type * * @param collectionClass generic Collection * @param elementClasses Element class * @return JavaType Java type * @since 1.0 */
public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
return objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
}
/** * take Map Convert to JavaBean * * @param map * @param clazz * @return */
public static <T> T map2pojo(Map map, Class<T> clazz) {
return objectMapper.convertValue(map, clazz);
}
/** * take Map Convert to JSON * * @param map * @return */
public static String mapToJson(Map map) {
try {
return objectMapper.writeValueAsString(map);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/** * take JSON Object to JavaBean * * @param obj * @param clazz * @return */
public static <T> T obj2pojo(Object obj, Class<T> clazz) {
return objectMapper.convertValue(obj, clazz);
}
}
版权声明
本文为[Zhenxiang]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220456034081.html
边栏推荐
- Chapter VIII affairs
- win10卡顿修复
- Several key points of logistic regression
- Discussion on data set division
- Boyun beyondcmp cloud management platform version 5.6 release
- Logistic regression -- case: cancer classification and prediction
- [stack and queue] simple application of C language ⌊ stack and queue realize each other, circular queue ⌉
- On the unsuccessful creation of SQLite database in Android development real machine debugging
- 博云 BeyondCMP 云管理平台 5.6 版本发布
- The urlcode of PHP cannot restore the original URL
猜你喜欢

2022 P cylinder filling training questions and answers

Carina local storage selected into the CNCF cloud native panorama

【板栗糖GIS】supermap—如何为数据制造超链接

2022 Shandong Province safety officer C certificate examination questions and online simulation examination

Spark starter: wordcount

Sharing of enterprise data leakage prevention scheme

Morphological operation of OpenCV image processing
Apple plans to expand children's information and communication security features to the UK and Canada
![[selenium] basic application of unittest testing framework](/img/17/b3d25b9eebccab37128e08bab4bd66.png)
[selenium] basic application of unittest testing framework
![[stack and queue] simple application of C language ⌊ stack and queue realize each other, circular queue ⌉](/img/ac/d0d76fd109a53da73c624631f90c00.png)
[stack and queue] simple application of C language ⌊ stack and queue realize each other, circular queue ⌉
随机推荐
在线预览PDF文件功能实现
2022t elevator repair test questions and online simulation test
MySQL forget root password solution
2022a special equipment related management (elevator) test question simulation test question bank simulation test platform operation
How to realize different values and display different colors in MATLAB
【Selenium】UnitTest测试框架的基本应用
2021-08-14
How the CPU calls the process
【板栗糖GIS】arcmap—模型构造器—批量裁剪栅格数据
On the unsuccessful creation of SQLite database in Android development real machine debugging
Junit常用注解
2021-08-14
【板栗糖GIS】supermap—如何为数据制造超链接
Extraction de la fonction Speech de l'ensemble de données emo - DB
Logistic regression -- case: cancer classification and prediction
Servlet lifecycle
QBoxSet、QBoxPlotSeries
Chapter I overview of database
Common commands of labelme
Setting method of parameters such as color and linetype of MATLAB curve