没学过Jackson,如何说学过电动汽车维修学校

jackson学习(二):jsonStringToObject(json字符串转自定义类) - 简书
jackson学习(二):jsonStringToObject(json字符串转自定义类)
说明:jackson介绍和maven配置在第一节说过了,有不明白的同学可以翻一翻第一节
参考项目:
开源地址:
个人博客:
1.编写测试代码
package com.cppba.
import com.fasterxml.jackson.annotation.JsonP
import com.fasterxml.jackson.databind.ObjectM
import java.io.IOE
import java.util.L
public class StringToObject {
public static void main(String[] args) throws IOException {
String jsonString = "{\"id\":\"1\",\"name\":\"bigbeef\",\"list\":[{\"str\":\"str1\",\"integer\":\"1\"}," +
"{\"str\":\"str2\",\"integer\":\"2\"}]}";
ObjectMapper objectMapper = new ObjectMapper();
MyObject myObject = objectMapper.readValue(jsonString, MyObject.class);
System.out.println(myObject.toString());
class MyObject{
@JsonProperty("id")
@JsonProperty("name")
@JsonProperty("list")
private List&MyListProject&
public String toString() {
return "MyObject{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", list=" + list +
class MyListProject{
@JsonProperty("str")
@JsonProperty("integer")
public String toString() {
return "MyListProject{" +
"str='" + str + '\'' +
", integer=" + integer +
2.运行结果
https://github.com/bigbeef
字符串转自定义类这种方式非常常见,比如在做微信开发、调用第三方接口时,返回的json字符串基本都是这种方式,如果你学到了这一节的方法,你的开发效率会提高很多!
java开发工程师
用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金Cover 有什么料? 从这篇文章中你能获得这些料: 知道setContentView()之后发生了什么? ... Android 获取 View 宽高的常用正确方式,避免为零 - 掘金相信有很多朋友...
用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你能获得这些料: 知道setContentView()之后发生了什么? ... Android 获取 View 宽高的常用正确方式,避免为零 - 掘金 相信有很多...
Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智能路由,微代理,控制总线)。分布式系统的协调导致了样板模式, 使用Spring Cloud开发人员可以快速地支持实现这些模式的服务和应用程序。他们将在任何分布式...
【转】Android 开源项目分类汇总 旭川君已关注
16:49*字数 29527阅读 1795评论 1喜欢 35 来源:https://github.com/Trinea/android-open-project 更多:Android 开源库获取途径...
中午骑车去拿快递,我骑得很急,因为军训的孩子们快解散了,想赶在他们之前去拿。无奈正好撞上,只好默默的排队,一边排一边听他们活泼俏皮的聊天。 不由的想起我的大一,那好像已成了一个遥不可及的回忆。 现在我回望那一段时光,烈日下的军训,社团里的奔波,以及独自异乡求学的孤独,竟然全...
文/黄老邪 公众号:黄老邪聊营销 hlxmarketing 罗一笑事件刷爆了朋友圈。这不是一件一笑而过的事情。具体的过程就不赘述了,从目前的阶段性调查来看,大家又被营销了。至于营销本身,没有价值观底线的营销只会让企业死的更快,煽动起来的浪潮不能愉悦消费者,必然会反噬自己。今...
平生最讨厌的两大家务活——洗衣服&洗碗。放假回家已经几天了,昨晚迫于老妈的言语逼迫,实现了归巢后第一次洗碗。洗着洗着,就想到:地球人为什么要在太空放音乐寻找外星人?能给予回复的“人”,智商不是更高,至少也要相当吧?人类何苦给自己找一个极可能比自己更强大的对手呢?突然就想起了...
像祖母绿一样,像绿碧玺一样,像孔雀石一样,纺织娘静悄悄地趴在一片草叶上,他微微抖着细长细长的触须,眼里映出夕阳的颜色,黄昏的颜色,然后是星空的颜色。他想,夜晚到了,这是影子铺满世界的时候,他要弹响风做的琴,吹鸣草做的萧,用今夜的第一颗露珠做鼓,摩挲他精妙的前足,唱送...
原来我是在渴望这个时刻,一个人默默倾听世界倾听自己。 生活真的需要这个状态存在,对于我而言。 没有平静下来的焦躁,没有安息下来的压抑,在脑海里胡搅蛮缠,一步步逼着健壮的心走向暗淡的深渊。 不知道该怎么安抚这不愿停止躁动。 原以为删去繁琐便能得到简约,却怎么也没想到所有的繁琐...JACKSON经典电动力学(下册).PDF
扫描二维码,下载文件到手机
相关文档推荐
当前文件信息
浏览:1524次
保存:24次
下载:388次
您的VIP会员已过期,是否续费?
用户应遵守著作权法,尊重著作权人合法权益,不违法上传、存储并分享他人作品。举报邮箱:
京网文[0号 京ICP证100780号Jackson 是一个能够将java对象序列化为JSON字符串,也能够将JSON字符串反序列化为java对象的框架。&
本文的所有内容都可以从&&中找到,这里记录下来供自己以后参考,如果时间充足,建议阅读原文。
这是另一篇介绍自定义(反)序列化的文章&
无论是序列化还是反序列化,Jackson都提供了三种方式:
1. JSON &--& Java Object&
2. JSON &--& JsonNode Tree(类似于XML的DOM树)
3.&JSON &--& Json Stream (这是一个低层次的api,很强大,但是很繁琐)
Jackson提供了很多有用的注解来定制序列化,但是我们完全不用它的注解也可以完成绝大多数的工作。下面就从上面三种方式来一一介绍。
JSON &--& Java Object&
下面的Person类是一个普通的java POJO。它含有基本类型(包括String、Date)和一些集合类型,以及一个自定义的Address类型。
注意: 默认情况下,Jackson会处理所有public的属性和拥有getter方法的属性(反序列化需要setter)
import java.util.ArrayL
import java.util.A
import java.util.D
import java.util.HashM
import java.util.L
import java.util.M
public class Person {
private int
private List&String& friends = new ArrayList&&();
public Map&String, String& info = new HashMap&&();
public String getName() {
public void setName(String name) {
this.name =
public int getAge() {
public void setAge(int age) {
this.age =
public List&String& getFriends() {
public void setFriends(List&String& friends) {
this.friends =
public Address getAddress() {
public void setAddress(Address address) {
this.address =
//注意这个默认构造器,如果没有默认的构造器,应该有一个@JsonCreator修饰的构造器
public Person(){}
public Person(String name, int age, Address address, Date birth, String... friends){
this.name =
this.age =
this.address =
this.birth =
this.friends.addAll(Arrays.asList(friends));
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("name: " + this.name + "\n");
sb.append("age: " + this.age + "\n");
sb.append("address: " + this.address + "\n");
sb.append("birth: " + this.birth + "\n");
this.friends.forEach(x -& sb.append("friend:"+ x + "\n"));
return sb.toString();
public class Address {
public String homeA
public String workA
//跟Person一样,我们也必须提供一个无参的默认构造器
public Address(){}
public Address(String homeAddress, String workAddress) {
this.homeAddress = homeA
this.workAddress = workA
public String toString() {
return "home:" + this.homeAddress + "
" + "work:" + this.workA
下面我们使用Jackson来(反)序列化 这个Person对象。
import java.io.F
import java.io.IOE
import java.text.ParseE
import java.text.SimpleDateF
import java.util.D
import com.fasterxml.jackson.core.JsonGenerationE
import com.fasterxml.jackson.databind.JsonMappingE
import com.fasterxml.jackson.databind.ObjectM
import com.fasterxml.jackson.databind.SerializationF
public class SerializeTest {
public static void main(String[] args) throws ParseException, JsonGenerationException, JsonMappingException, IOException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date birth = format.parse("");
Address address = new Address("New York", "Tokyo");
Person person = new Person("zhangsan", 11, address, birth, "weiying", "caifang");
person.info.put("height", "175cm");
person.info.put("weight", "80kg");
//使用ObjectMapper来序列化和反序列化
ObjectMapper mapper = new ObjectMapper();
//配置序列化的输出缩进
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
//如果没有DateFormat,ObjectMapper将会把Date类型序列化为毫秒数
mapper.setDateFormat(format);
//按照map的key的自然排序来产生序列化结果
mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
//序列化的过程就这一行代码,当然也可以选择输出到文件或其他流中
mapper.writeValue(new File("person.json"), person);
反序列化:
import java.io.F
import java.io.IOE
import com.fasterxml.jackson.core.JsonParseE
import com.fasterxml.jackson.databind.DeserializationF
import com.fasterxml.jackson.databind.JsonMappingE
import com.fasterxml.jackson.databind.ObjectM
public class DeserializeTest {
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
//反序列化同样从ObjectMapper开始
ObjectMapper mapper = new ObjectMapper();
//配置在反序列化过程中如果json字符串中存在无法匹配的属性不会失败
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//上面的configure(xxx,false) 等同于disable(xxx),例如下面这行和上面作用是一样的。
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
//反序列化的过程也仅仅只有一行代码,同样可以从文件或其他流等输入中进行反序列化
Person person = mapper.readValue(new File("person.json"), Person.class);
System.out.println(person);
&在上面的例子中我们看到了Jackson最基本的(反)序列化过程,下面我们介绍一些用来定制(反)序列化的注解:
1.@JsonProperty - 在默认情况下,Jackson会处理所有public的属性和拥有getter(序列化)和setter(反序列化)的属性。但是我们可以使用&@JsonProperty来手动指定我们希望jackson处理的属性。于此同时,我们可以改变java对象映射到json中的属性名称(默认是相同的)。@JsonProperty相当于JAXB中的@XmlElement注解。
import java.io.F
import java.io.IOE
import com.fasterxml.jackson.annotation.JsonP
import com.fasterxml.jackson.core.JsonGenerationE
import com.fasterxml.jackson.databind.JsonMappingE
import com.fasterxml.jackson.databind.ObjectM
import com.fasterxml.jackson.databind.SerializationF
* 这个Dog类型没有任何public的属性和getter方法,但是我们使用@JsonProperty可以手动指定希望(反)序列化的属性,并能指定希望映射到json中的属性名称
public class Dog {
@JsonProperty("dog_name")
private String name = "dahuang";
private int
@JsonProperty("dog_age")
private int tellYourAge(){
return this.
@JsonProperty("dog_age")
private void giveMeAge(int age){
this.age =
public String toString() {
return "dog(name: " + name + ";age: " + age + ")";
public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
//Jackson序列化空对象默认为失败
mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
//配置ObjectMapper有两种方式,除了上面那种,下面这行代码是等价的。
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
//配置序列化格式
mapper.enable(SerializationFeature.INDENT_OUTPUT);
//上面这行代码同样等价于下面这行
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
mapper.writeValue(new File("dog.json"), new Dog());
Dog dog = mapper.readValue(new File("dog.json"), Dog.class);
System.out.println(dog);
2.@JsonCreator - 在上面Person的例子中,我们除了定义了一个有参数的构造器外,还必须定义一个无参的默认构造器,这是因为在反序列化的过程中,Jackson不知道该向那个有参数的构造器中传递什么参数。 我们可以在构造器上使用 @JsonCreator,并在参数列表中使用@JsonProperty,这样在反序列化时Jackson就知道该如何使用这个构造器了,这个时候我们也就没必要定义那个无参的默认构造器了。
注意@JsonCreator仅仅在反序列化的过程中有用。
import java.io.F
import java.io.IOE
import com.fasterxml.jackson.annotation.JsonC
import com.fasterxml.jackson.annotation.JsonP
import com.fasterxml.jackson.core.JsonGenerationE
import com.fasterxml.jackson.databind.JsonMappingE
import com.fasterxml.jackson.databind.ObjectM
public class Dog {
public int
public String toString() {
return this.name + ":" + this.
//在反序列化的过程中,Jackson会将json串中的name属性传递给dog_name参数, 把json串中的age属性传递给dog_age参数。
@JsonCreator
public Dog(@JsonProperty("name") String dog_name, @JsonProperty("age") int dog_age){
this.name = dog_
this.age = dog_
public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("dog.json"), new Dog("dahuang", 11));
Dog dog = mapper.readValue(new File("dog.json"), Dog.class);
System.out.println(dog);
3.@JsonAnyGetter and @JsonAnySetter - 设想这样一种场景:除了java对象中明确指定的属性(包括使用@JsonProperty修饰指定的)外,我们希望能够随机的增加一些其他属性,让这些随机的属性也可以映射到json中去。这个时候我们就可以将这些不确定的属性放到一个map中去,并使用@JsonAnyGetter和@JsonAnySetter来修饰处理这个map的方法,然后Jackson就可以处理这些不确定的属性了。这两个属性相当于JAXB中的@XmlAnyElement和@XMLAnyAttribute。
import java.io.F
import java.io.IOE
import java.util.HashM
import java.util.M
import com.fasterxml.jackson.annotation.JsonAnyG
import com.fasterxml.jackson.annotation.JsonAnyS
import com.fasterxml.jackson.core.JsonGenerationE
import com.fasterxml.jackson.databind.JsonMappingE
import com.fasterxml.jackson.databind.ObjectM
public class Dog {
private Map&String, String& any = new HashMap&&();
@JsonAnyGetter
public Map&String, String& getAny(){
return this.
@JsonAnySetter
public void setAny(String key, String value){
this.any.put(key, value);
public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
Dog dog = new Dog();
//suck a big dog!!!
dog.setAny("height", "175cm");
dog.setAny("weight", "80kg");
ObjectMapper mapper = new ObjectMapper();
mapper.writerWithDefaultPrettyPrinter().writeValue(new File("dog.json"), dog);
Dog dog2 = mapper.readValue(new File("dog.json"), Dog.class);
dog2.getAny().forEach((x, y) -& System.out.println(x + "--&" + y));
4.@JsonIgnoreProperties and @JsonIgnore - 如果我们不希望Jackson处理java对象中public的属性或者拥有getter方法的属性,我们就可以使用这两个属性来忽略它们,相当于JAXB中@XmlTransient。
import java.io.IOE
import com.fasterxml.jackson.annotation.JsonI
import com.fasterxml.jackson.annotation.JsonIgnoreP
import com.fasterxml.jackson.core.JsonGenerationE
import com.fasterxml.jackson.databind.JsonMappingE
import com.fasterxml.jackson.databind.ObjectM
import com.fasterxml.jackson.databind.SerializationF
@JsonIgnoreProperties({"name", "age"})
public class Dog {
public String name = "dahuang";
public int age = 11;
@JsonIgnore
public String home = "CHN";
public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
//Dog的所有属性都已经被忽略了,所以此时应该序列化为一个空json串
mapper.writeValue(System.out, new Dog());
除了使用@JsonIgnoreProperties and @JsonIgnore来忽略特定属性外,还可以像下面这样忽略空的属性:
import java.io.IOE
import java.util.ArrayL
import java.util.L
import com.fasterxml.jackson.annotation.JsonInclude.I
import com.fasterxml.jackson.core.JsonGenerationE
import com.fasterxml.jackson.databind.JsonMappingE
import com.fasterxml.jackson.databind.ObjectM
import com.fasterxml.jackson.databind.SerializationF
public class Dog {
public String name = "";
public List&String& info = new ArrayList&&();
public List&String& info2 = null;
public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
//下面这行代码会忽略所有null或者空的属性,所以Dog此时依旧会被序列化为空JSON串
mapper.setSerializationInclusion(Include.NON_EMPTY);
mapper.writeValue(System.out, new Dog());
5.在序列化的过程中保存类型信息
下面定义了一个父类Animal和它的两个子类Dog和Cat,Person类有一个Animal类型的属性。
import com.fasterxml.jackson.annotation.JsonC
import com.fasterxml.jackson.annotation.JsonP
public class Animal {
public int
@JsonCreator
public Animal(@JsonProperty("name") String name, @JsonProperty("age") int age){
this.name =
this.age =
import com.fasterxml.jackson.annotation.JsonC
import com.fasterxml.jackson.annotation.JsonP
public class Dog extends Animal{
@JsonCreator
public Dog(@JsonProperty("name") String name, @JsonProperty("age") int age, @JsonProperty("size") String size){
super(name, age);
this.size =
import com.fasterxml.jackson.annotation.JsonC
import com.fasterxml.jackson.annotation.JsonP
public class Cat extends Animal{
@JsonCreator
public Cat(@JsonProperty("name") String name, @JsonProperty("age") int age, @JsonProperty("color") String color){
super(name, age);
this.color =
public class Person {
我们现在为Person的animal属性设置为Dog对象,然后序列化Person对象,之后再用得到的json串反序列化。
import java.io.F
import java.io.IOE
import com.fasterxml.jackson.core.JsonGenerationE
import com.fasterxml.jackson.databind.DeserializationF
import com.fasterxml.jackson.databind.JsonMappingE
import com.fasterxml.jackson.databind.ObjectM
public class Test {
public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
Person person = new Person();
person.animal = new Dog("dahuang", 11, "big");
ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.writeValue(new File("person.json"), person);
Person p2 = mapper.readValue(new File("person.json"), Person.class);
//在序列化的时候我们为Person对象animal属性赋予的是一个Dog对象,但是反序列化后得到的animal属性仅仅是一个animal对象。
//实际上,如果Animal是一个抽象类型的话,此时就会报错了。
System.out.println(p2.animal.getClass().getName());
在上面的例子序列化的结果是:
"animal" : {
"name" : "dahuang",
"age" : 11,
"size" : "big"
在上面的结果中我们看到Jackson并没有将animal属性的具体类型信息保存下来,这样在反序列化的时候,Jackson就无法知道之前序列化时的真正类型,这就是上面反序列化后得到的是一个Animal而不是Dog的原因。
我们修改Animal如下:
import com.fasterxml.jackson.annotation.JsonC
import com.fasterxml.jackson.annotation.JsonP
import com.fasterxml.jackson.annotation.JsonSubT
import com.fasterxml.jackson.annotation.JsonSubTypes.T
import com.fasterxml.jackson.annotation.JsonTypeI
import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = As.PROPERTY, property = "@class")
@JsonSubTypes({ @Type(value = Dog.class, name = "lion"), @Type(value = Cat.class, name = "elephant") })
public class Animal {
public int
@JsonCreator
public Animal(@JsonProperty("name") String name, @JsonProperty("age") int age){
this.name =
this.age =
然后再次执行上面那段序列化和反序列化的代码,便可以得到Person的animal属性是一个Dog对象了。 序列化的json为:
"animal" : {
"@class" : "com.massclouds.info.Dog",
"name" : "dahuang",
"age" : 11,
"size" : "big"
&我们看到上面的json结果中多了一个@class的属性,它就代表了animal属性的类型信息。
&当我们直接序列化一个Animal的list或者以Animal为value的map时,上面的设置依旧无法将类型信息保存到json串中,下面我们演示如何直接(反)序列化包含Animal的list和map(注意此时Animal上的注解依旧要有)。
import java.io.F
import java.io.IOE
import java.util.ArrayL
import java.util.HashM
import java.util.L
import java.util.M
import com.fasterxml.jackson.core.JsonGenerationE
import com.fasterxml.jackson.core.type.TypeR
import com.fasterxml.jackson.databind.JsonMappingE
import com.fasterxml.jackson.databind.ObjectM
import com.fasterxml.jackson.databind.SerializationF
public class SerializeList {
public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
List&Animal& animal_list = new ArrayList&&();
animal_list.add(new Dog("dahuang", 11, "big"));
animal_list.add(new Cat("miaomiao", 11, "grey"));
Map&String, Animal& animal_map = new HashMap&&();
animal_map.put("dog", new Dog("dahuagn", 11, "big"));
animal_map.put("cat", new Cat("miaomiao", 11, "white"));
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.writerFor(new TypeReference&List&Animal&&(){}).writeValue(new File("list.json"), animal_list);
mapper.writerFor(new TypeReference&Map&String, Animal&&(){}).writeValue(new File("map.json"), animal_map);
反序列化:
import java.io.F
import java.io.IOE
import java.util.L
import java.util.M
import com.fasterxml.jackson.core.JsonGenerationE
import com.fasterxml.jackson.core.type.TypeR
import com.fasterxml.jackson.databind.JsonMappingE
import com.fasterxml.jackson.databind.ObjectM
public class SerializeList {
public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
List&Animal& animal_list = mapper.readValue(new File("list.json"), new TypeReference&List&Animal&&(){});
animal_list.forEach(animal -& System.out.println(animal.getClass().getName()));
Map&String, Animal& animal_map = mapper.readValue(new File("map.json"), new TypeReference&Map&String, Animal&&(){});
animal_map.forEach((key, value) -& System.out.println(key + " --& " + value.getClass().getName()));
上面需要注意的地方就是 由于Class对象中是不能携带泛型信息的,所以需要使用TypeReference。
6. Mix-in&
当我们使用的是第三方类库中的Java类型时,我们无法直接在类型上使用注解,此时我们可以使用Jackson提供的Mix-in功能。
我们有一个Dog类如下:
public class Dog {
private int
public int getAge() {
public void setAge(int age) {
this.age =
public Dog(String name, int age){
this.name =
this.age =
我们需要定义一个抽象类,如果我们希望在Dog类的什么地方使用注解,我们就在这个抽象类中定义一个相同的声明(属性或者方法),然后使用注解,例如我们希望在Dog中的getAge方法上使用@JsonProperty注解,那么我们就在这个抽象类中定义一个名称为getAge的抽象方法,然后再在这个抽象方法上使用@JsonProperty。下面是这个抽象类的实现:
import com.fasterxml.jackson.annotation.JsonC
import com.fasterxml.jackson.annotation.JsonP
public abstract class DogMixin{
@JsonProperty("dog_name")
@JsonProperty("dog_age")
public abstract int getAge();
@JsonProperty("dog_age")
public abstract void setAge(int age);
@JsonCreator
public DogMixin(@JsonProperty("dog_name") String name,@JsonProperty("dog_age") int age){
//这里可以啥都没有。。。
然后在序列化的时候,像下面这样使用,就可以跟直接在Dog类中使用注解产生一样的效果了。
import java.io.F
import java.io.IOE
import com.fasterxml.jackson.core.JsonGenerationE
import com.fasterxml.jackson.databind.JsonMappingE
import com.fasterxml.jackson.databind.ObjectM
public class Test {
public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
//注册我们使用的Mixin抽象类
mapper.addMixIn(Dog.class, DogMixin.class);
Dog dog = new Dog("dahuang", 11);
mapper.writerWithDefaultPrettyPrinter().writeValue(new File("dog.json"), dog);
Dog dog2 = mapper.readValue(new File("dog.json"), Dog.class);
System.out.println(dog2.getAge() + " : " + dog2.name);
JSON &--& JsonNode Tree
就如同XML的DOM树一样,我们同样可以通过一颗json节点树来构建json,当然也可以将一个json字符串反序列化为一颗节点树。
import java.io.FileOutputS
import java.io.IOE
import com.fasterxml.jackson.core.JsonF
import com.fasterxml.jackson.core.JsonG
import com.fasterxml.jackson.databind.ObjectM
import com.fasterxml.jackson.databind.node.ArrayN
import com.fasterxml.jackson.databind.node.JsonNodeF
import com.fasterxml.jackson.databind.node.ObjectN
public class Tree2JSON {
public static void main(String[] args) throws IOException {
JsonFactory jsonFactory = new JsonFactory();
JsonGenerator generator = jsonFactory.createGenerator(new FileOutputStream("tree.json"));
ObjectMapper mapper = new ObjectMapper();
JsonNodeFactory factory = new JsonNodeFactory(false);
//生成一个根节点
ObjectNode person = factory.objectNode();
//普通属性直接添加即可
person.put("name", "zhangsan");
person.put("age",
//可以生成一个对象节点,然后把这个节点加入为根节点的子节点
ObjectNode address = factory.objectNode();
address.put("homeAddress", "New York");
address.put("workAddress", "Tokyo");
person.set("address", address);
//同样可以生成一个Array节点, 然后把这个Array节点加入为根节点的子节点
ArrayNode friends = factory.arrayNode();
ObjectNode friend1 = factory.objectNode();
friend1.put("name", "weiying");
ObjectNode friend2 = factory.objectNode();
friend2.put("name", "caifang");
friends.add(friend1).add(friend2);
person.set("friends", friends);
mapper.writeTree(generator, person);
产生的json字符串为(我不知道在这种情况下序列化这个JSON,要是你知道请告诉我):
{"name":"zhangsan","age":11,"address":{"homeAddress":"New York","workAddress":"Tokyo"},"friends":[{"name":"weiying"},{"name":"caifang"}]}
下面将这个JSON串反序列化为一颗树,并遍历这颗树:
import java.io.F
import java.io.IOE
import java.util.I
import com.fasterxml.jackson.core.JsonProcessingE
import com.fasterxml.jackson.databind.JsonN
import com.fasterxml.jackson.databind.ObjectM
import com.fasterxml.jackson.databind.node.ArrayN
import com.fasterxml.jackson.databind.node.JsonNodeT
public class JSON2Tree {
public static void main(String[] args) throws JsonProcessingException, IOException {
ObjectMapper mapper = new ObjectMapper();
// ObjectMapper读取json,返回根节点
JsonNode root = mapper.readTree(new File("tree.json"));
review(root);
// 递归遍历整棵树
private static void review(JsonNode root) {
if (root.getNodeType().equals(JsonNodeType.OBJECT)) {
Iterator&String& fieldNames = root.fieldNames();
while (fieldNames.hasNext()) {
String fieldName = fieldNames.next();
JsonNode node = root.get(fieldName);
System.out.println(fieldName);
review(node);
} else if (root.getNodeType().equals(JsonNodeType.ARRAY)) {
ArrayNode array = (ArrayNode)
Iterator&JsonNode& iter = array.iterator();
iter.forEachRemaining(x -& review(x));
System.out.println(root);
JSON &--& Json Stream&
Jackson提供了一种低层次的操作json的api,简单的说,就是Jackson读取json串后,会依次将json中的每个标志都产生相应的token,例如"{"表示对象的开始,那么Jackson 就产生一个表示对象开始的token。它很强大,但是很繁琐,不推荐使用。
import java.io.F
import java.io.IOE
import com.fasterxml.jackson.core.JsonF
import com.fasterxml.jackson.core.JsonParseE
import com.fasterxml.jackson.core.JsonP
import com.fasterxml.jackson.core.JsonT
public class StramParser {
public static void main(String[] args) throws JsonParseException, IOException {
JsonFactory factory = new JsonFactory();
JsonParser parser = factory.createParser(new File("person.json"));
while(!parser.isClosed()){
//这里仅仅简单的打印出token的类型和值(如果有的话)
JsonToken token = parser.nextToken();
System.out.println(token);
System.out.println(parser.getText());
import java.io.IOE
import com.fasterxml.jackson.core.JsonF
import com.fasterxml.jackson.core.JsonG
public class StreamGenerator {
public static void main(String[] args) throws IOException {
JsonFactory factory = new JsonFactory();
JsonGenerator generator = factory.createGenerator(System.out);
// start writing with {
generator.writeStartObject();
generator.writeFieldName("name");
generator.writeString("zhangsan");
generator.writeFieldName("address");
// start an array
generator.writeStartArray();
generator.writeStartObject();
generator.writeStringField("homeAddress", "New York");
generator.writeEndObject();
generator.writeStartObject();
generator.writeStringField("workAddress", "Tokyo");
generator.writeEndObject();
generator.writeEndArray();
generator.writeEndObject();
generator.close();
阅读(...) 评论()

我要回帖

更多关于 广州大学城电动车 的文章

 

随机推荐