最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Jackson庫中objectMapper的用法

 更新時間:2021年06月19日 17:19:02   作者:老周聊架構(gòu)  
這篇文章主要介紹了Jackson庫中objectMapper的用法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

Jackson庫中objectMapper用法

ObjectMapper類是Jackson庫的主要類。它提供一些功能將轉(zhuǎn)換成Java對象與SON結(jié)構(gòu)互相轉(zhuǎn)換,在項目中遇到過,故記錄一下。

在 pom.xml 加入依賴

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

創(chuàng)建一個實體類RiemannUser:

package com.test.objectMapper;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
/**
 * @author riemann
 * @date 2019/05/27 22:48
 */
public class RiemannUser implements Serializable {
    private static final long serialVersionUID = 1L;
    private int id;
    private String message;
    private Date sendDate;
    private String nodeName;
    private List<Integer> intList;
    public RiemannUser() {
        super();
    }
    public RiemannUser(int id, String message, Date sendDate) {
        super();
        this.id = id;
        this.message = message;
        this.sendDate = sendDate;
    }
    public static long getSerialVersionUID() {
        return serialVersionUID;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public Date getSendDate() {
        return sendDate;
    }
    public void setSendDate(Date sendDate) {
        this.sendDate = sendDate;
    }
    public String getNodeName() {
        return nodeName;
    }
    public void setNodeName(String nodeName) {
        this.nodeName = nodeName;
    }
    public List<Integer> getIntList() {
        return intList;
    }
    public void setIntList(List<Integer> intList) {
        this.intList = intList;
    }
    @Override
    public String toString() {
        return "RiemannUser{" + "id=" + id + ", message='" + message + '\'' + ", sendDate=" + sendDate + ", nodeName='" + nodeName + '\'' + ", intList=" + intList + '}';
    }
}

先創(chuàng)建一個ObjectMapper,然后賦值一些屬性:

public static ObjectMapper mapper = new ObjectMapper();
static {
    // 轉(zhuǎn)換為格式化的json
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    // 如果json中有新增的字段并且是實體類類中不存在的,不報錯
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}

1、對象與json字符串、byte數(shù)組

@Test
public void testObject() throws JsonGenerationException, JsonMappingException, IOException {
    RiemannUser riemann = new RiemannUser(1,"Hello World", new Date());
    mapper.writeValue(new File("D:/test.txt"), riemann);//寫到文件中
    //mapper.writeValue(System.out, riemann); //寫到控制臺
    String jsonStr = mapper.writeValueAsString(riemann);
    System.out.println("對象轉(zhuǎn)json字符串: " + jsonStr);
    byte[] byteArr = mapper.writeValueAsBytes(riemann);
    System.out.println("對象轉(zhuǎn)為byte數(shù)組:" + byteArr);
    RiemannUser riemannUser = mapper.readValue(jsonStr, RiemannUser.class);
    System.out.println("json字符串轉(zhuǎn)為對象:" + riemannUser);
    RiemannUser riemannUser2 = mapper.readValue(byteArr, RiemannUser.class);
    System.out.println("byte數(shù)組轉(zhuǎn)為對象:" + riemannUser2);
}

運行結(jié)果:

對象轉(zhuǎn)json字符串: {
"id" : 1,
"message" : "Hello World",
"sendDate" : 1558971056693,
"nodeName" : null,
"intList" : null
}
對象轉(zhuǎn)為byte數(shù)組:[B@31610302
json字符串轉(zhuǎn)為對象:RiemannUser{id=1, message='Hello World', sendDate=Mon May 27 23:30:56 CST 2019, nodeName='null', intList=null}
byte數(shù)組轉(zhuǎn)為對象:RiemannUser{id=1, message='Hello World', sendDate=Mon May 27 23:30:56 CST 2019, nodeName='null', intList=null}

2、list集合與json字符串

@Test
public void testList() throws JsonGenerationException, JsonMappingException, IOException {
    List<RiemannUser> riemannList = new ArrayList<>();
    riemannList.add(new RiemannUser(1,"a",new Date()));
    riemannList.add(new RiemannUser(2,"b",new Date()));
    riemannList.add(new RiemannUser(3,"c",new Date()));
    String jsonStr = mapper.writeValueAsString(riemannList);
    System.out.println("集合轉(zhuǎn)為字符串:" + jsonStr);
    List<RiemannUser> riemannLists = mapper.readValue(jsonStr, List.class);
    System.out.println("字符串轉(zhuǎn)集合:" + riemannLists);
}

運行結(jié)果:

集合轉(zhuǎn)為字符串:[ {
"id" : 1,
"message" : "a",
"sendDate" : 1558971833351,
"nodeName" : null,
"intList" : null
}, {
"id" : 2,
"message" : "b",
"sendDate" : 1558971833351,
"nodeName" : null,
"intList" : null
}, {
"id" : 3,
"message" : "c",
"sendDate" : 1558971833351,
"nodeName" : null,
"intList" : null
} ]
字符串轉(zhuǎn)集合:[{id=1, message=a, sendDate=1558971833351, nodeName=null, intList=null}, {id=2, message=b, sendDate=1558971833351, nodeName=null, intList=null}, {id=3, message=c, sendDate=1558971833351, nodeName=null, intList=null}]

3、map與json字符串

@Test
public void testMap() {
    Map<String, Object> testMap = new HashMap<>();
    testMap.put("name", "riemann");
    testMap.put("age", 27);
    testMap.put("date", new Date());
    testMap.put("user", new RiemannUser(1, "Hello World", new Date()));
    String jsonStr = null;
    try {
        jsonStr = mapper.writeValueAsString(testMap);
        System.out.println("Map轉(zhuǎn)為字符串:" + jsonStr);
        Map<String, Object> testMapDes = null;
        try {
            testMapDes = mapper.readValue(jsonStr, Map.class);
            System.out.println("字符串轉(zhuǎn)Map:" + testMapDes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
}

Map轉(zhuǎn)為字符串:{
"date" : 1558972169132,
"name" : "riemann",
"user" : {
"id" : 1,
"message" : "Hello World",
"sendDate" : 1558972169134,
"nodeName" : null,
"intList" : null
},
"age" : 27
}
字符串轉(zhuǎn)Map:{date=1558972169132, name=riemann, user={id=1, message=Hello World, sendDate=1558972169134, nodeName=null, intList=null}, age=27}

4、修改轉(zhuǎn)換時的日期格式:

@Test
public void testOther() throws IOException {
    // 修改時間格式
    mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    RiemannUser riemannUser = new RiemannUser(1,"Hello World",new Date());
    riemannUser.setIntList(Arrays.asList(1,2,3));
    String jsonStr = mapper.writeValueAsString(riemannUser);
    System.out.println("對象轉(zhuǎn)為字符串:" + jsonStr);
}

運行結(jié)果:

對象轉(zhuǎn)為字符串:{
"id" : 1,
"message" : "Hello World",
"sendDate" : "2019-05-27 23:53:55",
"nodeName" : null,
"intList" : [ 1, 2, 3 ]
}

objectMapper的一些坑

相信做過Java 開發(fā)對這個類應(yīng)該不陌生,沒錯,這個類是jackson提供的,主要是用來把對象轉(zhuǎn)換成為一個json字符串返回到前端,

現(xiàn)在大部分?jǐn)?shù)據(jù)交換都是以json來傳輸?shù)?所以這個很重要,那你到底又對這個類有著有多少了解呢,下面我說一下我遇到的一些坑

首先,先把我要說的幾個坑需要設(shè)置的屬性貼出來先

ObjectMapper objectMapper = new ObjectMapper();		
		//序列化的時候序列對象的所有屬性
		objectMapper.setSerializationInclusion(Include.ALWAYS);
		
		//反序列化的時候如果多了其他屬性,不拋出異常
		objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		
		//如果是空對象的時候,不拋異常
		objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
		
		//取消時間的轉(zhuǎn)化格式,默認(rèn)是時間戳,可以取消,同時需要設(shè)置要表現(xiàn)的時間格式
		objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
		objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))

簡單說一下這個類的基本用法,以下采用代碼塊加截圖的形式來說明和部分文字件數(shù)

package com.shiro.test; 
import java.text.SimpleDateFormat;
import java.util.Date; 
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature; 
public class Main2 {
	public static void main(String[] args) throws Exception{
		ObjectMapper objectMapper = new ObjectMapper();
		//序列化的時候序列對象的所有屬性
		objectMapper.setSerializationInclusion(Include.ALWAYS);
		//取消時間的轉(zhuǎn)化格式,默認(rèn)是時間戳,可以取消,同時需要設(shè)置要表現(xiàn)的時間格式
		objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
		objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
		
		Person person = new Person(1, "zxc", new Date());
		//這是最簡單的一個例子,把一個對象轉(zhuǎn)換為json字符串
		String personJson = objectMapper.writeValueAsString(person);
		System.out.println(personJson);
		
		//默認(rèn)為true,會顯示時間戳
		objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
		personJson = objectMapper.writeValueAsString(person);
		System.out.println(personJson);
	}
}

輸出的信息如下

objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)的作用

package com.shiro.test; 
import java.text.SimpleDateFormat;
import java.util.Date; 
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature; 
public class Main2 {
	public static void main(String[] args) throws Exception{
		ObjectMapper objectMapper = new ObjectMapper();
		//序列化的時候序列對象的所有屬性
		objectMapper.setSerializationInclusion(Include.ALWAYS);
		//如果是空對象的時候,不拋異常,也就是對應(yīng)的屬性沒有g(shù)et方法
		objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
		
		Person person = new Person(1, "zxc", new Date());
 
		String personJson = objectMapper.writeValueAsString(person);
		System.out.println(personJson);
		
		//默認(rèn)是true,即會拋異常
		objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, true);
		personJson = objectMapper.writeValueAsString(person);
		System.out.println(personJson);
	}
}

對應(yīng)的person類此時為

package com.shiro.test; 
import java.util.Date; 
public class Person { 
	private Integer id;
	private String name;
	private Date birthDate;
//	public Integer getId() {
//		return id;
//	}
//	public void setId(Integer id) {
//		this.id = id;
//	}
//	public String getName() {
//		return name;
//	}
//	public void setName(String name) {
//		this.name = name;
//	}
//	public Date getBirthDate() {
//		return birthDate;
//	}
//	public void setBirthDate(Date birthDate) {
//		this.birthDate = birthDate;
//	}
	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", birthDate=" + birthDate + "]";
	}
	public Person(Integer id, String name, Date birthDate) {
		super();
		this.id = id;
		this.name = name;
		this.birthDate = birthDate;
	}
	
	public Person() {
		// TODO Auto-generated constructor stub
	}
}

結(jié)果如下

package com.shiro.test; 
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper; 
public class Main2 {
	public static void main(String[] args) throws Exception{
		ObjectMapper objectMapper = new ObjectMapper();
		//序列化的時候序列對象的所有屬性
		objectMapper.setSerializationInclusion(Include.ALWAYS);
		//反序列化的時候如果多了其他屬性,不拋出異常
		objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		
//		Person person = new Person(1, "zxc", new Date());
 
//		String personJson = objectMapper.writeValueAsString(person);
//		System.out.println(personJson);
		
		//注意,age屬性是不存在在person對象中的
		String personStr = "{\"id\":1,\"name\":\"zxc\",\"age\":\"zxc\"}";
		
		Person person = objectMapper.readValue(personStr, Person.class);
		System.out.println(person);
		
		//默認(rèn)為true
		objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
		person = objectMapper.readValue(personStr, Person.class);
		System.out.println(person);		
	}
}

執(zhí)行后的結(jié)果如下

這些便是這幾個屬性的作用所以,由于第一個比較簡單我就這樣說一下吧

Include.ALWAYS 是序列化對像所有屬性

Include.NON_NULL 只有不為null的字段才被序列化

Include.NON_EMPTY 如果為null或者 空字符串和空集合都不會被序列化

然后再說一下如何把一個對象集合轉(zhuǎn)換為一個 Java里面的數(shù)組

package com.shiro.test; 
import java.util.ArrayList;
import java.util.Date;
import java.util.List; 
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
 
public class Main2 {
	public static void main(String[] args) throws Exception{
		ObjectMapper objectMapper = new ObjectMapper();
		//序列化的時候序列對象的所有屬性
		objectMapper.setSerializationInclusion(Include.NON_DEFAULT);
		
		Person person1 = new Person(1, "zxc", new Date());
		Person person2 = new Person(2, "ldh", new Date());
		
		List<Person> persons = new ArrayList<>();
		persons.add(person1);
		persons.add(person2);
		
		//先轉(zhuǎn)換為json字符串
		String personStr = objectMapper.writeValueAsString(persons);
		
		//反序列化為List<user> 集合,1需要通過 TypeReference 來具體傳遞值
		List<Person> persons2 = objectMapper.readValue(personStr, new TypeReference<List<Person>>() {});
		
		for(Person person : persons2) {
			System.out.println(person);
		}
		
		//2,通過 JavaType 來進(jìn)行處理返回
		JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, Person.class);
		List<Person> persons3 = objectMapper.readValue(personStr, javaType);
		
		for(Person person : persons3) {
			System.out.println(person);
		}
	}
}

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java Swing仿QQ登錄界面效果

    Java Swing仿QQ登錄界面效果

    這篇文章主要為大家詳細(xì)介紹了Java Swing仿QQ登錄界面效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-05-05
  • mybatis-plus配置控制臺打印完整帶參數(shù)SQL語句的實現(xiàn)

    mybatis-plus配置控制臺打印完整帶參數(shù)SQL語句的實現(xiàn)

    這篇文章主要介紹了mybatis-plus配置控制臺打印完整帶參數(shù)SQL語句,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-08-08
  • Java實現(xiàn)Redis延時消息隊列

    Java實現(xiàn)Redis延時消息隊列

    本文主要介紹了Java實現(xiàn)Redis延時消息隊列,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-08-08
  • SpringBoot2新特性 自定義端點詳解

    SpringBoot2新特性 自定義端點詳解

    這篇文章主要介紹了SpringBoot2新特性 自定義端點詳解,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • WIN10環(huán)境 Maven的安裝與配置詳細(xì)教程

    WIN10環(huán)境 Maven的安裝與配置詳細(xì)教程

    這篇文章主要介紹了WIN10環(huán)境 Maven的安裝與配置詳細(xì)教程,本文分步驟給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-09-09
  • Java實現(xiàn)AWT四大事件的詳細(xì)過程

    Java實現(xiàn)AWT四大事件的詳細(xì)過程

    AWT的事件處理是一種委派式事件處理方式:普通組件(事件源)將整個事件處理委托給特定的對象(事件監(jiān)聽器);當(dāng)該事件源發(fā)生指定的事件時,就通知所委托的事件監(jiān)聽器,由事件監(jiān)聽器來處理這個事件
    2022-04-04
  • MyBatis中高級多表查詢(ResultMap、association、collection)詳解

    MyBatis中高級多表查詢(ResultMap、association、collection)詳解

    文章主要介紹了MyBatis中高級多表查詢的四種方式:ResultMap、association、collection以及自連接查詢,通過定義接口的抽象方法、編寫mapper.xml和測試類,詳細(xì)展示了如何根據(jù)復(fù)雜數(shù)據(jù)結(jié)構(gòu)進(jìn)行數(shù)據(jù)的裝配和查詢,感興趣的朋友一起看看吧
    2024-11-11
  • java IO 字節(jié)流詳解及實例代碼

    java IO 字節(jié)流詳解及實例代碼

    這篇文章主要介紹了java IO 字節(jié)流詳解及實例代碼的相關(guān)資料,需要的朋友可以參考下
    2017-03-03
  • 基于RabbitMQ幾種Exchange 模式詳解

    基于RabbitMQ幾種Exchange 模式詳解

    下面小編就為大家?guī)硪黄赗abbitMQ幾種Exchange 模式詳解。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-11-11
  • 如何利用 Either 和 Option 進(jìn)行函數(shù)式錯誤處理

    如何利用 Either 和 Option 進(jìn)行函數(shù)式錯誤處理

    這篇文章主要介紹了如何利用 Either 和 Option 進(jìn)行函數(shù)式錯誤處理。在 Java 中,錯誤的處理在傳統(tǒng)上由異常以及創(chuàng)建和傳播異常的語言支持進(jìn)行。但是,如果不存在結(jié)構(gòu)化異常處理又如何呢?,需要的朋友可以參考下
    2019-06-06

最新評論

兰坪| 阜新| 阿克苏市| 宁波市| 湖口县| 巴林左旗| 白水县| 漳州市| 京山县| 石首市| 新泰市| 和平区| 襄垣县| 邯郸市| 白山市| 九龙坡区| 巩留县| 双峰县| 宣化县| 镇原县| 和静县| 新安县| 绥化市| 富宁县| 南雄市| 临夏市| 金坛市| 水富县| 定陶县| 潍坊市| 沈阳市| 孟州市| 乌苏市| 保德县| 姜堰市| 监利县| 高要市| 河西区| 饶阳县| 呼伦贝尔市| 汽车|