Java一般操作 对象序列化和反序列化

对象序列化和反序列化

码代码

测试

    @Test
    public void testProc5(){

        Employee employee = new Employee();
        Employee employee2 = new Employee();
        String employeeStr;

        employee.setName("暗室逢灯");
        employee.setAge(26);

        /**
         * JSONObject.toJSONString(Object)
         * 此方法将指定的对象序列化为其等效的Json表示形式。
         * 请注意,如果任何对象字段都是一般类型,则此方法可以正常工作,只是对象本身不是一般类型此方法可能无法工作。
         * 如果您想将对象写入Writer,请使用writeJSONString(写入器、对象、SerializerFeature[])。
         */
        employeeStr = JSONObject.toJSONString(employee);
        System.out.println(employeeStr);

        /**
         * JSONObject.parseObject(String)
         * 该方法把字符串转换为JSONObject
         *
         * toJavaObject(Class)
         * 该方法把JSONObject转换为指定类的对象
         */
        employee2 = JSONObject.parseObject(employeeStr).toJavaObject(Employee.class);

        System.out.println(employee2);
    }

结果输出

{"age":26,"name":"暗室逢灯"}
Employee{id=null, name='暗室逢灯', age=26, salary=null}

POJO

package cn.Entity;

import java.io.Serializable;


public class Employee implements Serializable {
    private Integer id;
    private String name;
    private Integer age;
    private Float salary;

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", salary=" + salary +
                '}';
    }

    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 Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Float getSalary() {
        return salary;
    }

    public void setSalary(Float salary) {
        this.salary = salary;
    }

    public Employee(Integer id, String name, Integer age, Float salary) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    public Employee() {
    }
}

对象序列化中字段为Null的处理

忽略Null字段

		String string  = JSON.toJSONString(list, SerializerFeature.WriteMapNullValue);

显示Null字段

        Employee employee = new Employee();
        employee.setName("aaa");
        String string  = JSON.toJSONString(employee, SerializerFeature.WRITE_MAP_NULL_FEATURES ,SerializerFeature.PrettyFormat  );
        System.out.println(string);

Web项目下非Spring托管类中拿Spring Bean的方法

            WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
            Object obj = wac.getBean(UserInfoDao.class);

java.security.InvalidKeyException: Illegal key size

为了数据代码在传输过程中的安全,很多时候我们都会将要传输的数据进行加密,然后等对方拿到后再解密使用。我们在使用AES加解密的时候,在遇到128位密钥加解密的时候,没有进行什么特殊处理;然而,在使用256位密钥加解密的时候,如果不进行特殊处理的话,往往会出现这个异常java.security.InvalidKeyException: Illegal key size。

为什么会产生这样的错误?

JDK中包含有JRE(Java Runtime Environment,即:Java运行环境),JRE中包括Java虚拟机(Java
Virtual Machine)、Java核心类库和支持文件。在Java的核心类库中有一个JCE(Java Cryptography
Extension),JCE是一组包,它们提供用于加密、密钥生成和协商以及 Message Authentication
Code(MAC)算法的框架和实现,所以这个是实现加密解密的重要类库。

在我们安装的JRE目录下有这样一个文件夹:%JAVE_HOME%\jre\lib\security(%JAVE_HOME%是自己电脑的Java路径,一版默认是:C:\Program
Files\Java,具体看自己当时安装JDK和JRE时选择的路径是什么),其中包含有两个.jar文件:“local_policy.jar
”和“US_export_policy.jar”,也就是我们平时说的jar包,再通俗一点说就是Java中包含的类库(Sun公司的程序大牛封装的类库,供使用Java开发的程序员使用),这两个jar包就是我们JCE中的核心类库了。JRE中自带的“local_policy.jar
”和“US_export_policy.jar”是支持128位密钥的加密算法,而当我们要使用256位密钥算法的时候,已经超出它的范围,无法支持,所以才会报:“java.security.InvalidKeyException:
Illegal key size or default parameters”的异常。

解决方案:去官方下载JCE无限制权限策略文件。

JDK7的下载地址: http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
JDK8的下载地址: http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html

在这里插入图片描述
用jce policy解压后的包去覆盖jre security下的文件,然后重启出现异常的程序就ok了。

实例Slf4j的Logger

private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(HomeController.class);

Redis持久化过程中出错解决

出错日志:

MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on disk. Commands that may modify the data set are disabled. Please check Redis logs for details about the error.

MISCONF Redis被配置为保存RDB快照,但目前无法在磁盘上存留。可能修改数据集的命令被禁用。请检查Redis日志,了解有关错误的详细信息。

在redis-cli下输入:

config set stop-writes-on-bgsave-error no

Tomcat启动随机数生成过慢

启动日志:

31-Oct-2019 14:27:07.400 INFO [main] org.apache.catalina.core.StandardService.startInternal Starting service [Catalina]
31-Oct-2019 14:27:07.400 INFO [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet Engine: Apache Tomcat/8.5.45
31-Oct-2019 14:27:07.407 INFO [localhost2w-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/usr/local/apache-tomcat-8.5.45/webapps/manager]
31-Oct-2019 14:27:07.702 INFO [localhost2w-startStop-1] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.

卡在这里几分钟甚至十多分钟才能完全启动。

原因:Tomcat的random生成随机数太慢。
tomcat/bin/下的
setenv.sh里增加

JAVA_OPTS="$JAVA_OPTS -Djava.security.egd=file:/dev/urandom"

替换tomcat本身的random,提升tomcat启动速度。


Docker 错误响应:TLS握手超时

我们在使用docker去search、pull 镜像的时候可能会遇到的 response异常:

Error response from daemon: Get https://index.docker.io/v1/search?q=mongo&n=25: net/http: TLS handshake timeout

使用dig命令找到可用的IP

[root@localhost ~]# dig @114.114.114.114 registry-1.docker.io

; <<>> DiG 9.11.4-P2-RedHat-9.11.4-9.P2.el7 <<>> @114.114.114.114 registry-1.docker.io
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 62765
;; flags: qr rd ra; QUERY: 1, ANSWER: 8, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;registry-1.docker.io.          IN      A

;; ANSWER SECTION:
registry-1.docker.io.   30      IN      A       34.199.77.19
registry-1.docker.io.   30      IN      A       3.224.75.242
registry-1.docker.io.   30      IN      A       3.224.11.4
registry-1.docker.io.   30      IN      A       3.226.66.79
registry-1.docker.io.   30      IN      A       3.221.133.86
registry-1.docker.io.   30      IN      A       34.197.189.129
registry-1.docker.io.   30      IN      A       3.210.179.11
registry-1.docker.io.   30      IN      A       34.199.40.84

;; Query time: 14 msec
;; SERVER: 114.114.114.114#53(114.114.114.114)
;; WHEN: Sat Dec 07 06:58:22 EST 2019
;; MSG SIZE  rcvd: 177

如果没有dig命令:

yum install bind-utils

/etc/hosts 配置映射


34.199.40.84    registry-1.docker.io 

然后再去pull和search就okay了。

MyBatis:Dao方法not found绑定异常

项目运行时出现的MyBatis异常:org.apache.ibatis.binding.BindingException: Invalid bound statement (not found) 异常

org.apache.ibatis.binding.BindingException:
		Invalid bound statement (not found): com.kev.team.sys.dao.SysUserInfoDao.getBackList
		org.apache.ibatis.binding.MapperMethod$SqlCommand.<init>(MapperMethod.java:178)
		org.apache.ibatis.binding.MapperMethod.<init>(MapperMethod.java:38)
		org.apache.ibatis.binding.MapperProxy.cachedMapperMethod(MapperProxy.java:49)
		org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:42)
		com.sun.proxy.$Proxy94.getBackList(Unknown Source)

引发这个异常的原因常常是我们自己在配置MyBatis时粗心遗漏或者写错了配置项:

1、Mapper的xml配置文件包路径写错、namespace、resultType、resultMap。

2、还有一个是在MyBatis的mapper包扫描路径遗漏,比如下面这个:
在这里插入图片描述
修正配置,rebuild,run 项目检测结果。

Idea启动junit测试方法异常Command line is too long

Error running 'TestClass.testProc': Command line is too long. Shorten command line for TestClass.testProc or also for Android JUnit default configuration.

解决方式,改变运行命令
在这里插入图片描述

在这里插入图片描述

Springboot Web项目下非Spring托管类中拿Spring Bean的方法

@Component
@Lazy(false)
public class ApplicationContextRegister implements ApplicationContextAware {
    private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationContextRegister.class);
    private static ApplicationContext APPLICATION_CONTEXT;
    /**  * 设置spring上下文  *  * @param applicationContext spring上下文  * @throws BeansException  */
    @Override  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        LOGGER.debug("ApplicationContext registed-->{}", applicationContext);
        APPLICATION_CONTEXT = applicationContext;
    }
        public static ApplicationContext getApplicationContext() { return APPLICATION_CONTEXT;  }
}

            wxOpenBusinessService = ApplicationContextRegister.getApplicationContext().getBean(WxOpenBusinessService.class);

fastjson反序列化java date

@JSONField(format = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
private Date createdAt;
@JSONField(format = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
private Date updatedAt;
{
"createdAt":"2019-12-12T14:53:14.015331+08:00",
"updatedAt":"2021-10-12T15:55:03.751704+08:00"
}

java用fastjson反序列化模板类

                if (JSONValidator.from(body).validate()) {
                    JSONObject jsonObject = JSON.parseObject(body);
                    System.out.println(jsonObject);

                    Result<UserInfo> userInfos = new Result<>();
                    userInfos = jsonObject.toJavaObject(new TypeReference<Result<UserInfo>>(){});

                    System.out.println(JSON.toJSONString(userInfos));

                }

spring web项目下非controller过程中获取request、response

        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        HttpServletResponse response = servletRequestAttributes.getResponse();
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值