java用Json将父类转成子类
json
适用于现代 C++ 的 JSON。
项目地址:https://gitcode.com/gh_mirrors/js/json
免费下载资源
·
将父类对象用 JSONObject.toJSONString(father)转成String,
再用JSONObject.parseObject 转成子类对象
Son son2= JSONObject.parseObject(JSONObject.toJSONString(father),Son.class);
不一定是要父类子类的关系,只要有相同属性的都可以转;
示范代码,父类:
public class Father<T> {
private String name;
private int age;
private double score;
private List<T> 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<T> getData() {
return data;
}
public void setData(List<T> 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<String> 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转成功
GitHub 加速计划 / js / json
41.72 K
6.61 K
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:1 个月前 )
960b763e
4 个月前
8c391e04
6 个月前
更多推荐
已为社区贡献5条内容
所有评论(0)