Java Jackson - Json Polymorphism

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() + "]";

    }

}

时间: 2024-10-11 05:39:58

Java Jackson - Json Polymorphism的相关文章

Java之JSON操作(Jackson)

Java to JSON: 1 package json.jackson; 2 3 import bean.User; 4 import com.fasterxml.jackson.databind.ObjectMapper; 5 6 import java.io.File; 7 import java.util.Map; 8 9 /** 10 * Jackson – Java to JSON 11 * 功能:JSON与Java对象.Map等类型转换,JSON文件的读写等 12 * 依赖包:ja

java系列--JSON数据的处理

http://blog.csdn.net/qh_java/article/details/38610599 http://www.cnblogs.com/lanxuezaipiao/archive/2013/05/23/3096001.html java处理JSON的框架就我目前知道的有3种: 1.Jackson框架: 提供两个类 JsonGenerator    ObjectMapper 2.josn-lib框架:提供的主要类有 JSONObject      JSONArray 3.org-

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

我们都知道,Jackson JSON以高速.方便和灵活著称.之前的文章中介绍过使用注解的形式来规定如何将一个对象序列化成JSON的方法,以及如何将一个JSON数据反序列化到一个对象上.但是美中不足的一点就是对于中文的处理.当然我说的美中不足是在默认情况下,Jackson JSON不会将中文等非ASCII字符转换为\uFFFF这样的形式来显示.也就是说默认情况下会显示为{"name":"张三"}而不是{"name":"\u5F20\u4E

Jackson JSON Processor

Jackson提供接口,可以再json和bean之间互相转换 1. 一个例子 public class JsonToJavaBean { public static void main(String[] args) { String str="{\"student\":[{\"name\":\"leilei\",\"age\":23},{\"name\":\"leilei02\"

jackson json和对象,集合的几种转换

jackson  json和对象,集合的几种转换 package com.crm.net.util; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; import org.codehaus.jackson.JsonParseException

Jackson JSON对日期格式的解析设置

服务器端:采用Spring MVC3 + MyBatis3架构设计,使用Jackson JSON将Java对象转换成JSON格式: Spring:3.2.2.RELEASE MyBatis:3.2.1 mybatis-spring:1.2.0 前端:采用jQuery EasyUI框架,使用 jquery-json-2.4.js 将javascript对象转换成JSON格式: 交互方式:服务器端和前端采用json格式进行数据交互. 遇到问题:服务器端对Java对象序列化后,日期格式为一长串数字(如

Java解析JSON对象

今天学习一下Java 解析 JSON 准备工作 参考文档 1) www.json.org 2 ) 参考公司其他人的代码(这个就不说了) 依赖jar包 1) org.json.jar 提供以下我的网盘链接 http://pan.baidu.com/s/1jG2zSwe 主要的类 JSON主要有两种结构 1)name/value 的集合 2)value 的集合,在大多数语言中的list,array等,这里的 value 个人觉得就是一个JSON,也就是说是JSON的集合 JAVA处理JSON的类 1

java处理json与对象的转化 递归

整个类是一个case,总结了我在使用java处理json的时候遇到的问题,还有级联关系的对象如何遍历,json和对象之间的转换! 对于对象json转换中遇到的问题我参考了一篇博客,http://blog.csdn.net/xq328220454/article/details/39256589 很有益处,我在文章的后半部分照搬了过来! 首先准备数据,准备了一堆具有主子关系的对象,包含普通属性id,父对象parent,子集合list<HeadCell>,还有关联对象message; 1 @Bef

java to Json or Json to JavaBean

今天练习,放这里,以后再补充 这里使用的jar包是 net.sf.json.JSONObject package yh.test.t1118; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import yh.com.entity.User; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by Ad