使用json序列化java对象

使用单元测试方法用json序列化与反序列化java对象

需要引入的jar包:

jackson-annotations-2.9.9.jar
jackson-core-2.9.9.jar
jackson-databind-2.9.9.jar
junit-4.12.jar

类文件 Person.java

package cn.tedu.seri;

import java.io.Serializable;

/**
 * @author "孤影"
 * 2019年10月16日
 * 下午4:49:13
 */
//序列化:把java对象转成json保存到磁盘里/out的过程
public class Person implements Serializable{
	/**
	 * 序列化版本号
	 */
	private static final long serialVersionUID = 1L;
	
 	private String name = "hanmeijuan";
	private int age = 10;
	 
	/**
	 * 默认无参构造
	 */
	public Person() {
		super();
	}
	/**
	 * @param name
	 * @param age
	 */
	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}
	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}
	/**
	 * @return the age
	 */
	public int getAge() {
		return age;
	}
	/**
	 * @param age the age to set
	 */
	public void setAge(int age) {
		this.age = age;
	}
	/**
	 * @return the serialversionuid
	 */
	public static long getSerialversionuid() {
		return serialVersionUID;
	}
}

具体操作方法类: Test1_Seria.java

package cn.tedu.seri;

import org.junit.Test;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author "孤影"
 * 2019年10月16日
 * 下午4:51:43
 */
//序列化:把java对象转成json保存到磁盘里/out的过程
public class Test1_Seria {
	//序列化
	@Test
	public void seria() throws Exception {
		Person p = new Person();//实例化对象
		//把对象转成json : jackson -- ObjectMapper
		ObjectMapper mapper = new ObjectMapper();
		//p是指定要转换的对象
		String json = mapper.writeValueAsString(p);
		System.out.println(json);
	}
	//反序列化
	@Test 
	public void deseri() throws Exception {
		//创建json
		String json = "{\"name\":\"蔡徐坤\",\"age\":20}";
		// 把对象转成json : jackson -- ObjectMapper
		ObjectMapper mapper = new ObjectMapper();
		
		Person p = mapper.readValue(json, Person.class);
		System.out.println(p.getAge()+" "+p.getName());
	}
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值