jackson配置和解析JSON

jackson配置和解析JSON

jackson是Java語言中最通用的JSON解析庫

Maven中添加jackson依賴

1、打開目錄下的pom.xml

2、在project中加入以下代碼

<dependencies>
     <dependency>
         <groupId>com.fasterxml.jackson.core</groupId>
         <artifactId>jackson-databind</artifactId>
         <version>2.9.6</version>
     </dependency>
</dependencies>

3、在IDEA編輯器下,右擊選擇Maven,點擊Reimport,即可完成

基本使用

可以參考別人寫的一篇博客

https://blog.csdn.net/u011054333/article/details/80504154

核心的是使用ObjectMapper類進行對JSON的處理

readValue可以從文件或者字符串中獲得JSON對象並轉換爲Java對象

下面舉一些例子

讀取

可以用Map來接收,格式上是一一對應的

ObjectMapper objectMapper = new ObjectMapper();

Map map =objectMapper.readValue(
	new File("./data.json"),Map.class
);

也可以用List來接收,但需要進行一些處理。

 List<DemoClass> redPackList = 
 	objectMapper.readValue(file,
          new TypeReference<List<DemoClass>>() {
    });

也可用String

String jsonContent = objectMapper.writeValueAsString(DemoClass);

objectMapper.readValue(jsonContent,DemoClass.class);

寫入

objectMapper.writeValue(file, demoClassList);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章