【Java】将Java对象序列化/反序列化为JSON,并写入redis

RedisUtil类和spring_config.xml配置文件在这篇文章:【Redis】Spring集成Redis  中给出了,这里不再赘述。

① 依赖导入

 
        
            com.alibaba
            fastjson
            1.2.12
        

②User实体类

package com.cqh.PojoToJson;

/**
 * Created by yl1794 on 2018/4/2.
 */
public class User {

        private String id;
        private String name;
        private String password;
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
        @Override
        public String toString() {
            return "User [id=" + id + ", name=" + name + ", password=" + password
                    + "]";
        }
}

③测试类

package com.cqh.PojoToJson;

import com.alibaba.fastjson.JSON;
import com.cqh.Cache_Spring_Redis.RedisUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Created by yl1794 on 2018/4/2.
 */
public class Test_PojoToJson_Redis {
    public static void main(String[] args){
        ApplicationContext context = new ClassPathXmlApplicationContext("spring_config.xml");
        RedisUtil redisUtil = (RedisUtil)context.getBean("redisUtil");

        User userToJson = new User();
        userToJson.setId("150327003");
        userToJson.setName("cqh");
        userToJson.setPassword("123456");

        // 将Java对象序列化为JSON,并写入redis
        System.out.println(JSON.toJSONString(userToJson));
        redisUtil.set("userToJson", JSON.toJSONString(userToJson));

        // 直接取出来是一个Object
        System.out.println( redisUtil.get("userToJson"));

        // 反序列化为User对象
        User jsonToUser = JSON.parseObject( redisUtil.get("userToJson").toString(), User.class);
        System.out.println(jsonToUser);

    }
}

④结果

【Java】将Java对象序列化/反序列化为JSON,并写入redis_第1张图片

【Java】将Java对象序列化/反序列化为JSON,并写入redis_第2张图片

你可能感兴趣的:(Java,Redis)