from://http://www.studytrails.com/java/json/java-jackson-Serialization-polymorphism.jsp

Jackson provides a way to maintain sub type information while serializing java objects. It is possible to recreate the exact sub type. The type information can be embedded into the json as a property. In the example below we create a zoo, that has a list of animals. The animal may be an elephant or a lion, and they both extend the Animal abstract class. While deserializing we want to create the exact animal type. We also demonstrate the use of @JsonTypeInfo and @JsonSubTypes annotations.

Data Serialization and Polymorphism Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.studytrails.json.jackson;
 
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
 
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
 
public class SerializeExample1 {
    private static String outputFile = "zoo.json";
 
    public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
        // let start creating the zoo
        Zoo zoo = new Zoo("Samba Wild Park""Paz");
        Lion lion = new Lion("Simba");
        Elephant elephant = new Elephant("Manny");
        List<Animal> animals = new ArrayList<>();
        animals.add(lion);
        animals.add(elephant);
        zoo.setAnimals(animals);
 
        ObjectMapper mapper = new ObjectMapper();
        mapper.writerWithDefaultPrettyPrinter().writeValue(new FileWriter(new File(outputFile)), zoo);
    }
}

Before we look at the various classes, lets also see how to deserialize this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.studytrails.json.jackson;
 
import java.io.File;
import java.io.IOException;
 
import org.apache.commons.io.FileUtils;
 
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
 
public class DeSerializeExample1 {
 
    public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
        ObjectMapper mapper = new ObjectMapper();
        Zoo zoo = mapper.readValue(FileUtils.readFileToByteArray(new File("zoo.json")), Zoo.class);
        System.out.println(zoo);
    }
}

Zoo class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.studytrails.json.jackson;
 
import java.util.List;
 
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
 
@JsonTypeInfo(use = JsonTypeInfo.Id.MINIMAL_CLASS, include = As.PROPERTY, property = "@class")
public class Zoo {
 
    public String name;
    public String city;
    public List<Animal> animals;
 
    @JsonCreator
    public Zoo(@JsonProperty("name") String name, @JsonProperty("city") String city) {
        this.name = name;
        this.city = city;
    }
 
    public void setAnimals(List<animal> animals) {
        this.animals = animals;
    }
 
    @Override
    public String toString() {
        return "Zoo [name=" + name + ", city=" + city + ", animals=" + animals + "]";
    }
 
}
 
 
</animal>

Animal Abstract class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.studytrails.json.jackson;
 
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
 
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = As.PROPERTY, property = "@class")
@JsonSubTypes({ @Type(value = Lion.class, name = "lion"), @Type(value = Elephant.class, name = "elephant") })
public abstract class Animal {
    @JsonProperty("name")
    String name;
    @JsonProperty("sound")
    String sound;
    @JsonProperty("type")
    String type;
    @JsonProperty("endangered")
    boolean endangered;
 
}

Lion class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.studytrails.json.jackson;
 
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
 
public class Lion extends Animal {
 
    private String name;
 
    @JsonCreator
    public Lion(@JsonProperty("name") String name) {
        this.name = name;
    }
 
    public String getName() {
        return name;
    }
 
    public String getSound() {
        return "Roar";
    }
 
    public String getType() {
        return "carnivorous";
    }
 
    public boolean isEndangered() {
        return true;
    }
 
    @Override
    public String toString() {
        return "Lion [name=" + name + ", getName()=" + getName() + ", getSound()=" + getSound() + ", getType()=" + getType() + ", isEndangered()="
                + isEndangered() + "]";
    }
 
}

Elephant class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.studytrails.json.jackson;
 
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
 
public class Elephant extends Animal {
 
    @JsonProperty
    private String name;
 
    @JsonCreator
    public Elephant(@JsonProperty("name") String name) {
        this.name = name;
    }
 
    public String getName() {
        return name;
    }
 
    public String getSound() {
        return "trumpet";
    }
 
    public String getType() {
        return "herbivorous";
    }
 
    public boolean isEndangered() {
        return false;
    }
 
    @Override
    public String toString() {
        return "Elephant [name=" + name + ", getName()=" + getName() + ", getSound()=" + getSound() + ", getType()=" + getType()
                ", isEndangered()=" + isEndangered() + "]";
    }
 
}

Java Jackson - Json Polymorphism的更多相关文章

  1. Java之JSON操作(Jackson)

    Java to JSON: package json.jackson; import bean.User; import com.fasterxml.jackson.databind.ObjectMa ...

  2. Java解析json(二):jackson

    Java解析json(二):jackson   官方参考 Jackson Home Page:https://github.com/FasterXML/jackson Jackson Wiki:htt ...

  3. Java 的 JSON 开源类库选择比较(zz)

    在看了作者的介绍,然后我又到mvnrepository上去看了各个库的的使用数之后,发现只能在jackson和gson之间做选择. 以下是原文 有效选择七个关于Java的JSON开源类库 April  ...

  4. java系列--JSON数据的处理

    http://blog.csdn.net/qh_java/article/details/38610599 http://www.cnblogs.com/lanxuezaipiao/archive/2 ...

  5. Java JWT: JSON Web Token

    Java JWT: JSON Web Token for Java and Android JJWT aims to be the easiest to use and understand libr ...

  6. 开源 JSON 库解析性能对比( Jackson / Json.simple / Gson )

    Json 已成为当前服务器与 web 应用之间数据传输的公认标准. 微服务及分布式架构经常会使用 Json 来传输此类文件,因为这已经是 webAPI 的事实标准. 不过正如许多我们习以为常的事情一样 ...

  7. 让Jackson JSON生成的数据包含的中文以unicode方式编码

      本文出处:http://blog.csdn.net/chaijunkun/article/details/8257209,转载请注明.由于本人不定期会整理相关博文,会对相应内容作出完善.因此强烈建 ...

  8. 如何让Jackson JSON生成的数据包含的中文以unicode方式编码

    我们都知道,Jackson JSON以高速.方便和灵活著称.之前的文章中介绍过使用注解的形式来规定如何将一个对象序列化成JSON的方法,以及如何将一个JSON数据反序列化到一个对象上.但是美中不足的一 ...

  9. java中 json和bean list map之间的互相转换总结

    JSON 与 对象 .集合 之间的转换 JSON字符串和java对象的互转[json-lib]   在开发过程中,经常需要和别的系统交换数据,数据交换的格式有XML.JSON等,JSON作为一个轻量级 ...

随机推荐

  1. pom配置之:<distributionManagement>snapshot快照库和release发布库

    本文转载自:  铁木箱子的mzone的博客: http://www.mzone.cc/article/277.html http://www.mzone.cc/article/279.html 在使用 ...

  2. 浅谈js设计模式 — 享元模式

    享元(flyweight)模式是一种用于性能优化的模式,“fly”在这里是苍蝇的意思,意为蝇量级.享元模式的核心是运用共享技术来有效支持大量细粒度的对象. 假设有个内衣工厂,目前的产品有 50种男式内 ...

  3. HTTPS-加密SSL证书

    从第一部分HTTP工作原理中,我们可以了解到HTTPS核心的一个部分是数据传输之前的握手,握手过程中确定了数据加密的密码.在握手过程中,网站会向浏览器发送SSL证书,SSL证书和我们日常用的身份证类似 ...

  4. wpf 如果列表加载超多数据变的卡顿时,使用VirtualizingStackPanel

    如果列表加载超多数据变的卡顿时 <ListBox > <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <Virt ...

  5. jQuery.lazyload详解(转)

    转自:http://www.cnblogs.com/wenbo/archive/2011/07/15/2107579.html <script type="text/javascrip ...

  6. 前端架构之路:Windows下安装Nodejs步骤

      最近打算把我们的微信端用Vue.js重构,为什么选择Vue.js,一是之前使用的是传统的asp.net mvc,多页面应用用户体验比单页面要差.二是使用过Angular.js,感觉对开发人员要求较 ...

  7. Python中collections.defaultdict()使用

    一个小示例 from collections import defaultdict import json def tree(): return defaultdict(tree) users = t ...

  8. 005.FTP本地用户访问

    一 新建本地用户 [root@imxhy ftp]# useradd ftpuser #用于登陆ftp的用户 [root@imxhy ftp]# passwd ftpuser Changing pas ...

  9. hdu4055

    hdu4055 题意 给出一个长度为 n - 1 的字符串,要求构造一个包含数字 [1, n] 的排列,从第二位开始,'I' 表示当前位数字比前一位大,'D' 表示当前位数字比前一位小,'?' 表示可 ...

  10. C#开发Unity游戏教程之Scene视图与脚本的使用

    C#开发Unity游戏教程之Scene视图与脚本的使用 Unity中Scene视图的快捷操作 Scene视图是开发者开发游戏时,操作最频繁的视图.因为一旦一个游戏对象被添加到游戏的场景中,就需要首先使 ...