fastJson converts a string into a generic object

Use the official TypeReference to convert generic objects

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import lombok.Data;

public class Type {
    
    

    @Data
    public static class Response<T> {
    
    
        private Integer code;
        private String msg;
        private T data;
    }

    @Data
    public static class Student {
    
    
        private String name;
        private String no;
    }

    public static void main(String[] args) {
    
    
        String ret = "{\"code\":-1,\"msg\":\"参数不合法\",\"data\":{\"name\":\"小明\",\"no\":\"123456\"}}";
        Response<Student> response = JSONObject.parseObject(ret, new TypeReference<Response<Student>>(){
    
    });
        System.out.println(response.getData().getNo());
        System.out.println(response.getData().getName());
    }

}

Guess you like

Origin blog.csdn.net/fomeiherz/article/details/103606228