TestJsonDateSerializer.java 1.54 KB
package com.zhaoonline.common.json;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.junit.Assert;
import org.junit.Test;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;

public class TestJsonDateSerializer {
	@Test
	public void testDateParse() throws JsonProcessingException{
		ObjectMapper mapper= new ObjectMapper();
		SimpleModule module = new SimpleModule();
		module.addSerializer(Date.class, new JsonDateSerializer());
		mapper.registerModule(module);
		
		TestDateObject o=new TestDateObject();
		o.setDate(new Date(System.currentTimeMillis()));
		System.out.println(mapper.writeValueAsString(o));;
	}
	
	
	@Test
	public void testDateParseWithJsonUtils() throws JsonProcessingException {
		
		TestDateObject object=new TestDateObject();
		object.setDate(new Date(System.currentTimeMillis()));
		System.out.println(JsonUtils.toJson(object));;
	}
	
	
	@Test
	public void testDateDeserialWithJsonUtils() throws ParseException, IOException {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String testDateString="{\"date\":\"2016-11-01 19:28:38\",\"name\":null,\"id\":null}";
		
		TestDateObject testDate=JsonUtils.toObject(testDateString, TestDateObject.class);
		Assert.assertEquals(dateFormat.parse("2016-11-01 19:28:38") , testDate.getDate());
		Assert.assertNull(testDate.getId());
		Assert.assertNull(testDate.getName());
	}
	
	
	
}