Java使用ObjectMapper的簡單示例
一、什么是ObjectMapper?
- ObjectMapper類是Jackson庫的主要類,它提供一些功能將數(shù)據(jù)集或對象轉換的實現(xiàn)。
- 它將使用JsonParser和JsonGenerator實例來實現(xiàn)JSON的實際讀/寫。
二、ObjectMapper怎么使用?
2.1 配置
2.1.1 普通Java項目(引入如下依賴即可)
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.5</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.5</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.9.5</version> </dependency>
2.1.2 Sring Boot項目
重要說明:
由于Spring Boot的自動配置JacksonAutoConfiguration中有如下圖所示的依賴引入和配置,所以不需要我們額外配置


2.2 實戰(zhàn)
User類
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class User implements Serializable {
private static final long serialVersionUID = 1L;
// 姓名
private String name;
// 性別
private String sex;
// 年齡
private Integer age;
}
2.2.1 Java對象、集合轉JSON
public static void main(String[] args) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
User user = new User();
user.setName("張三");
user.setAge(20);
user.setSex("男");
List<User> userList = new ArrayList<>();
userList.add(user);
// 對象轉換為JSON
String userJsonString = objectMapper.writeValueAsString(user);
// 集合轉換為JSON
String userListJsonString = objectMapper.writeValueAsString(userList); }
2.2.2 JSON轉Java對象、集合
// JOSN轉對象(java對象)
User newUser = objectMapper.readValue(userJsonString, User.class);
// JOSN轉集合(集合)
List<User> list = objectMapper.readValue(userListJsonString, new TypeReference<List<User>>(){});
2.2.3json轉JsonNode、ObjectNode
說明:
Jackson的JsonNode和ObjectNode兩個類,前者是不可變的,一般用于讀取。后者可變,一般用于創(chuàng)建Json對象圖。
// json轉JsonNode
JsonNode jsonNode = objectMapper.readTree(userJsonString);
String sex = jsonNode.get("sex").asText();
// JsonNode轉ObjectNode
ObjectNode objectNode = (ObjectNode)jsonNode;
// json轉JsonNode
JsonNode jsonNodeList = objectMapper.readTree(userListJsonString);
// JsonNode轉ObjectNode
ArrayNode arrayNode = (ArrayNode)jsonNodeList;
2.2.4 jsonNode轉對象、集合
// jsonNode轉為json字符串
String jsonNodeString = objectMapper.writeValueAsString(jsonNode);
String jsonNodeListString = objectMapper.writeValueAsString(jsonNodeList);
// json字符串轉對象、集合
User user1 = objectMapper.readValue(jsonNodeString, User.class);
List<User> list1 = objectMapper.readValue(jsonNodeListString, new TypeReference<List<User>>() {});
2.3 注意事項
2.3.1微服務中從其他服務獲取過來的對象,如果從Object強轉為自定義的類型會報錯,利用ObjectMapper轉換。
正確示例:
說明:Schedule類、OutpOrderBill類都是類似于User類的Java對象。
// 對象
Schedule schedule = objectMapper.convertValue(callNurseCenterService.getSchedule(registRecord.getScheCode()).getData(), Schedule.class);
// 泛型為對象的集合
List<OutpOrderBill> outpOrderBillList = objectMapper.convertValue(
callChargeCenterService.getOrderBillByOrderCode(orders.getOrgCode(),orders.getOrderCode()).getData(),
new TypeReference<List<OutpOrderBill>>() {});
2.3.2 上面轉換的過程中,如果返回的字段你不是都需要,需要忽略其中的幾個字段,在自定義的類中添加標紅注解
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@JsonIgnoreProperties(ignoreUnknown = true)
public class User implements Serializable {
private static final long serialVersionUID = 1L;
////提供有這個參數(shù),但是不想獲取
// // 姓名
// private String name;
// 性別
private String sex;
// 年齡
private Integer age;
}
如果不想添加注解,可以使用下面兩種方式
第一種方式:
ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD,Visibility.ANY); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
第二種方式:
ObjectMapper objectMapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
2.3.3 在轉換的過程中,有可能有的屬性被設成空就不序列化等的需求,可以在類的屬性上或直接在類上加上一下注解。用在屬性上就是只針對一個屬性,用在類上就是針對類里的所有屬性。
@JsonInclude(Include.NON_NULL) @JsonInclude(Include.Include.ALWAYS) 默認 @JsonInclude(Include.NON_DEFAULT) 屬性為默認值不序列化 @JsonInclude(Include.NON_EMPTY) 屬性為 空(“”) 或者為 NULL 都不序列化 @JsonInclude(Include.NON_NULL) 屬性為NULL 不序列化
參考網(wǎng)址:
到此這篇關于Java使用ObjectMapper的簡單示例的文章就介紹到這了,更多相關Java使用ObjectMapper內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
MyBatis注解開發(fā)-@Insert和@InsertProvider的使用
這篇文章主要介紹了MyBatis注解開發(fā)-@Insert和@InsertProvider的使用,具有很好的參考價值,希望對大家有所幫助。2022-07-07
Spring中BeanFactoryPostProcessors是如何執(zhí)行的
BeanFactoryPostProcessor是Spring容器提供的一個擴展機制,它允許開發(fā)者在Bean的實例化和初始化之前對BeanDefinition進行修改和處理,這篇文章主要介紹了你知道Spring中BeanFactoryPostProcessors是如何執(zhí)行的嗎,需要的朋友可以參考下2023-11-11
Java使用Lettuce客戶端在Redis在主從復制模式下命令執(zhí)行的操作
這篇文章主要介紹了Java使用Lettuce客戶端在Redis在主從復制模式下命令執(zhí)行的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04

