java用Json将父类转成子类

将父类对象用 JSONObject.toJSONString(father)转成String,

再用JSONObject.parseObject 转成子类对象

Son son2= JSONObject.parseObject(JSONObject.toJSONString(father),Son.class);

不一定是要父类子类的关系,只要有相同属性的都可以转;

 

示范代码,父类:

public class Father {
    private String name;
    private int age;
    private double score;
    private List data;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

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

    public double getScore() {
        return score;
    }

    public void setScore(double score) {
        this.score = score;
    }

    public List getData() {
        return data;
    }

    public void setData(List data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "Father{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", score=" + score +
                ", data=" + data +
                '}';
    }

    public static void main(String[] args) {
        Father father =new Father();
        father.setAge(18);
        father.setName("yiqian");
        father.setScore(99.99);
        List list=new ArrayList<>();
        list.add("hello");
        list.add("world");
        father.setData(list);
        try {
            Son son1= (Son) father;
            System.out.println("son1 class="+son1.getClass().getName());
            System.out.println("son1 name="+son1.getName());
        }catch (Exception e){
            System.out.println(e);
        }
        Son son2= JSONObject.parseObject(JSONObject.toJSONString(father),Son.class);
        System.out.println("son2 class="+son2.getClass().getName());
        System.out.println("son2 name="+son2.getName());
        System.out.println("son2 age="+son2.getAge());
        System.out.println("son2 score="+son2.getScore());
        System.out.println("son2 data="+son2.getData());
        System.out.println("teacher2 weight="+son2.getNickName());
    }
}

子类:

public class Son extends Father {

    private String nickName;

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }
}

 

运行父类中的main方法,强转失败,用json转成功

java用Json将父类转成子类_第1张图片

 

 

你可能感兴趣的:(java)