JackSon 支持三种序列化 与 三种反序列化 方式 :
下面分别对 反序列化 与 序列化 进行讲解
3种 反序列化方式:
1.从文件中的json串 反序列化
2.从url 中获取字符串 进行 反序列化
3.从字符串进行反序列化
示例:
MyValue.java
package model;
//Note: can use getters/setters as well; here we just use public fields directly:
public class MyValue {
public String name;
public int age;
// NOTE: if using getters/setters, can keep fields `protected` or `private`
// public MyValue(String name, int age) {
// // TODO Auto-generated constructor stub
// this.name = name;
// this.age = age;
// }
@Override
public String toString() {
// TODO Auto-generated method stub
return "name: "+ this.name + "\n"+
"age: " + this.age + "\n";
}
}
反序列化 代码片段
ObjectMapper mapper = new ObjectMapper();
//Json 转换为 Java类, 反序列化
//** 方式一 : 从文件中读取
MyValue fromFile = mapper.readValue(new File("data.json"), MyValue.class);
System.out.println(fromFile);
//** 方式二 : 从url中的返回值中读取
// MyValue fromUrl = mapper.readValue(new URL("http://some.com/api/entry.json"), MyValue.class);
// System.out.println(fromUrl);
//** 方式三 : 从字符串中读取
//jackson 不支持 单引号 , 如:"{'name':'Szh', 'age':24}"
//会报错
// Exception in thread "main" com.fasterxml.jackson.core.JsonParseException: Unexpected character (''' (code 39)): was expecting double-quote to start field name
// at [Source: {'name':'Szh', 'age':24}; line: 1, column: 3]
MyValue fromjson = mapper.readValue("{\"name\":\"Szh\", \"age\":24}", MyValue.class);
System.out.println(fromjson);
额外教程: list, map, pojo 的反序列化
Map<String, Integer> scoreByName = mapper.readValue(jsonSource, Map.class);
List<String> names = mapper.readValue(jsonSource, List.class);
// and can obviously write out as well
// mapper.writeValue(new File("names.json"), names);
// as long as JSON structure matches, and types are simple. If you have POJO values, you need to indicate actual type (note: this is NOT needed for POJO properties with List etc types):
Map<String, ResultValue> results = mapper.readValue(jsonSource,
new TypeReference<Map<String, ResultValue>>() { } );
// why extra work? Java Type Erasure will prevent type detection otherwise
注意:
使用 jackson 包将 json字符串进行反序列化时,如果定义了内部类的话,这个内部类必须用 static 修饰,否则序列化会出错。具体的原因见Jackson and Inner Classes: yes, you can use, but they must be STATIC inner classes.
============================
3种 序列化方式:
1.将java对象进行序列化, 将序列化后的串写入到文件中。
2.按照字节数组的形式返回json串
3.按照字符数组的形式返回json串
序列化 代码片段
ObjectMapper mapper = new ObjectMapper();
//Java类 转换为 Json串 , 序列化
MyValue serializeClass = new MyValue();
serializeClass.age = 22;
serializeClass.name = "sxHJ";
//方法一 : 将序列化后的串写入到文件中
mapper.writeValue(new File("result.json"), serializeClass);
//方式二: 按照字节数组的形式返回json串
byte[] jsonBytes = mapper.writeValueAsBytes(serializeClass);
System.out.println(jsonBytes);
//方式三: 按照字符数组的形式返回json串
String jsonString = mapper.writeValueAsString(serializeClass);
System.out.println(jsonString);
完整代码 以及结果:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>JacksonTest</groupId>
<artifactId>JacksonTest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>jackson</name>
<properties>
<jackson.version>2.8.4</jackson.version>
</properties>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<!-- Note: core-annotations version x.y.0 is generally compatible with
(identical to) version x.y.1, x.y.2, etc. -->
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
代码
import java.io.File;
import java.io.IOException;
import model.MyValue;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonFirst {
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
//Json 转换为 Java类, 反序列化
//** 方式一 : 从文件中读取
MyValue fromFile = mapper.readValue(new File("data.json"), MyValue.class);
System.out.println(fromFile);
//** 方式二 : 从url中的返回值中读取
// MyValue fromUrl = mapper.readValue(new URL("http://some.com/api/entry.json"), MyValue.class);
// System.out.println(fromUrl);
//** 方式三 : 从字符串中读取
//jackson 不支持 单引号 , 如:"{'name':'Szh', 'age':24}"
//会报错
// Exception in thread "main" com.fasterxml.jackson.core.JsonParseException: Unexpected character (''' (code 39)): was expecting double-quote to start field name
// at [Source: {'name':'Szh', 'age':24}; line: 1, column: 3]
MyValue fromjson = mapper.readValue("{\"name\":\"Szh\", \"age\":24}", MyValue.class);
System.out.println(fromjson);
//Java类 转换为 Json串 , 序列化
MyValue serializeClass = new MyValue();
serializeClass.age = 22;
serializeClass.name = "sxHJ";
//方法一 : 将序列化后的串写入到文件中
mapper.writeValue(new File("result.json"), serializeClass);
//方式二: 按照字节数组的形式返回json串
byte[] jsonBytes = mapper.writeValueAsBytes(serializeClass);
System.out.println(jsonBytes);
//方式三: 按照字符数组的形式返回json串
String jsonString = mapper.writeValueAsString(serializeClass);
System.out.println(jsonString);
}
}