Bootstrap

Json字符串转换成泛型类

1. pom.xml引入fastjson依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.62</version>
</dependency>

2. 泛型类例子

注意:这里我们一定要有无参构造方法,因为在转换时会用到反射进行实例化类,用的是无参构造方法,所以一定要有无参构造方法,而且还一定要有setter方法,因为在实例化过后会用setter方法对属性进行复制,如果没有setter方法那么这个属性就会是对应的默认值如:integer 为null。

import lombok.Data;

@Data
public class NorthResult<T> {
    private Integer type;
    private String message;
    private String errorMessage;
    private T data;

    public NorthResult(Integer type, String message, String errorMessage) {
        this.type = type;
        this.message = message;
        this.errorMessage = errorMessage;
    }
     public NorthResult() {

    }

     public NorthResult(Integer type, String message, String errorMessage, T data) {
        this.type = type;
        this.message = message;
        this.errorMessage = errorMessage;
        this.data = data;
    }

}

UserCellZipperRespDto.class

@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserCellZipperRespDto implements Serializable {

    private Integer totalCnt;

    private List<UserCellZipperDetail> details;
}

3. 转换方法

3.1 用JSON.parseObject方法进行转换

public class Application {
    public static void main(String[] args) {
        String s = "{\\\"type\\\":0,\\\"message\\\":\\\"\\\",\\\"errorMessage\\\":\\\"\\\",\\\"data\\\":{\\\"totalCnt\\\":29,\\\"details\\\":[{\\\"msisdn\\\":\\\"16619886880\\\",\\\"rat\\\":6,\\\"lacci\\\":\\\"6306_27025971\\\",\\\"entryTime\\\":1657672349,\\\"entryTimeStr\\\":\\\"2022-07-13 08:32:29.000\\\",\\\"leaveTime\\\":1657672509,\\\"stayTimeSpan\\\":160,\\\"longitude\\\":116.41028,\\\"latitude\\\":40.08639}]}}"
    NorthResult<UserCellZipperRespDto> response = JSON.parseObject(s, new TypeReference<NorthResult<UserCellZipperRespDto>>(){});
        System.out.println(response);

    }
}

;