栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

用Jackson将反序列化的JSON转换为多态类型

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

用Jackson将反序列化的JSON转换为多态类型

如所承诺的,我将举一个如何使用注释对多态对象进行序列化/反序列化的示例,该示例基于

Animal
您正在阅读的教程中的类。

首先,在您的

Animal
类中使用子类的Json注释。

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;import com.fasterxml.jackson.annotation.JsonSubTypes;import com.fasterxml.jackson.annotation.JsonTypeInfo;@JsonIgnoreProperties(ignoreUnknown = true)@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY)@JsonSubTypes({    @JsonSubTypes.Type(value = Dog.class, name = "Dog"),    @JsonSubTypes.Type(value = Cat.class, name = "Cat") })public abstract class Animal {    private String name;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }}

然后是您的子类

Dog
Cat

public class Dog extends Animal {    private String breed;    public Dog() {    }    public Dog(String name, String breed) {        setName(name);        setBreed(breed);    }    public String getBreed() {        return breed;    }    public void setBreed(String breed) {        this.breed = breed;    }}public class Cat extends Animal {    public String getFavoriteToy() {        return favoriteToy;    }    public Cat() {}    public Cat(String name, String favoriteToy) {        setName(name);        setFavoriteToy(favoriteToy);    }    public void setFavoriteToy(String favoriteToy) {        this.favoriteToy = favoriteToy;    }    private String favoriteToy;}

如您所见,

Cat
and并没有什么特别的
Dog
,唯一了解它们的是
abstract
class
Animal
,因此在反序列化时,您将定位到
Animal
并且
ObjectMapper
将返回实际实例,如以下测试所示:

public class Test {    public static void main(String[] args) {        ObjectMapper objectMapper = new ObjectMapper();        Animal myDog = new Dog("ruffus","english shepherd");        Animal myCat = new Cat("goya", "mice");        try { String dogJson = objectMapper.writevalueAsString(myDog); System.out.println(dogJson); Animal deserializedDog = objectMapper.readValue(dogJson, Animal.class); System.out.println("Deserialized dogJson Class: " + deserializedDog.getClass().getSimpleName()); String catJson = objectMapper.writevalueAsString(myCat); Animal deseriliazedCat = objectMapper.readValue(catJson, Animal.class); System.out.println("Deserialized catJson Class: " + deseriliazedCat.getClass().getSimpleName());        } catch (Exception e) { e.printStackTrace();        }    }}

运行

Test
该类后的输出:

{"@type":"Dog","name":"ruffus","breed":"english shepherd"}

Deserialized dogJson Class: Dog

{"@type":"Cat","name":"goya","favoriteToy":"mice"}

Deserialized catJson Class: Cat

希望这可以帮助,

何塞·路易斯



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/371147.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号