jackson序列化与反序列化

 笔者在使用SSM框架项目部分功能进行测试需要使用到对象的序列化与反序列化

Demo

package com.dznfit.service;

import com.dznfit.controller.LoginController;
import com.dznfit.entity.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import javaConfiguration.RootConfig;
import javaConfiguration.WebConfig;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import the_mass.redis.SerializeUtil;

import java.io.IOException;
import java.util.ArrayList;


public class UserServiceImplTest {
    private static Logger logger = Logger.getLogger(UserServiceImplTest.class);

    @Test
    public void login() throws IOException {
        User user = new User(1, "dz", "123", 1);
        //放入容器
        AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext(RootConfig.class);
        //得到bean
        UserServiceImpl bean = context.getBean(UserServiceImpl.class);
        /**
         * ObjectMapper是JSON操作的核心,Jackson的所有JSON操作都是在ObjectMapper中实现。
         */
        ObjectMapper mapper = new ObjectMapper();

        System.out.println("类名" + bean.login((user)).getClass().getName());
        String s = mapper.writeValueAsString(bean.login(user));

        System.out.println("序列化:" + s);
        
        System.out.println("反序列化:" + mapper.readValue(s, User.class));
    }
}

结果:

我们可以看到jackson实现类

ObjectMapper有许多方法
序列化时给个Object对象就可以了转成json字符串
反序列化也是有很多

亲自试一试吧

猜你喜欢

转载自www.cnblogs.com/dzcici/p/10183436.html