1.Maven Dependency
<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>org.fool.jackson</groupId> <artifactId>Jackson</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>Jackson</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.1.3</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.1</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> </dependencies> </project>
2.Project Directory
工程中JavaObjectToJson.java 和 JsonToJavaObject.java,在Jackson Basic(http://agilestyle.iteye.com/blog/1779257)中已列举,这里不再赘述。
3.POJO
User.java
package org.fool.jackson;
import java.util.List;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
public class User
{
private String name;
private int age;
private List<String> msgs;
public User()
{
}
public User(String name, int age, List<String> msgs)
{
this.name = name;
this.age = age;
this.msgs = msgs;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public List<String> getMsgs()
{
return msgs;
}
public void setMsgs(List<String> msgs)
{
this.msgs = msgs;
}
@Override
public String toString()
{
return ToStringBuilder.reflectionToString(this,
ToStringStyle.SHORT_PREFIX_STYLE);
}
}
4.JUnit Test
JacksonTest.java基本框架如下
package org.fool.jackson;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
public class JacksonTest
{
private JsonGenerator jsonGenerator = null;
private ObjectMapper objectMapper = null;
private User user = null;
@Before
public void setUp()
{
List<String> msgs = new ArrayList<>();
msgs.add("msg1");
msgs.add("msg2");
msgs.add("msg3");
user = new User("Hero", 30, msgs);
objectMapper = new ObjectMapper();
try
{
jsonGenerator = objectMapper.getFactory().createJsonGenerator(
System.out, JsonEncoding.UTF8);
}
catch (IOException e)
{
e.printStackTrace();
}
}
@After
public void tearDown()
{
try
{
if (jsonGenerator != null)
{
jsonGenerator.flush();
}
if (!jsonGenerator.isClosed())
{
jsonGenerator.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
......
}
writeEntity2Json
...
@Test
public void writeEntity2Json()
{
try
{
System.out.println("jsonGenerator");
jsonGenerator.writeObject(user);
System.out.println();
System.out.println("objectMapper");
objectMapper.writeValue(new File("Entity2Json.json"), user);
objectMapper.writeValue(System.out, user);
}
catch (JsonGenerationException e)
{
e.printStackTrace();
}
catch (JsonMappingException e)
{
e.printStackTrace();
}
catch (JsonProcessingException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
...
result
jsonGenerator
{"name":"Hero","age":30,"msgs":["msg1","msg2","msg3"]}
objectMapper
{"name":"Hero","age":30,"msgs":["msg1","msg2","msg3"]}
writeList2Json
...
@Test
public void writeList2Json()
{
List<User> list = new ArrayList<>();
list.add(user);
try
{
System.out.println("jsonGenerator");
jsonGenerator.writeObject(list);
System.out.println();
System.out.println("objectMapper");
objectMapper.writeValue(new File("List2Json.json"), list);
objectMapper.writeValue(System.out, list);
}
catch (JsonGenerationException e)
{
e.printStackTrace();
}
catch (JsonMappingException e)
{
e.printStackTrace();
}
catch (JsonProcessingException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
...
result
jsonGenerator
[{"name":"Hero","age":30,"msgs":["msg1","msg2","msg3"]}]
objectMapper
[{"name":"Hero","age":30,"msgs":["msg1","msg2","msg3"]}]
writeMap2Json
...
@Test
public void writeMap2Json()
{
Map<String, Object> map = new HashMap<>();
map.put("name", user.getName());
map.put("age", user.getAge());
map.put("msg", user.getMsgs());
map.put("user", user);
try
{
System.out.println("jsonGenerator");
jsonGenerator.writeObject(map);
System.out.println();
System.out.println("objectMapper");
objectMapper.writeValue(new File("Map2Json.json"), map);
objectMapper.writeValue(System.out, map);
}
catch (JsonGenerationException e)
{
e.printStackTrace();
}
catch (JsonMappingException e)
{
e.printStackTrace();
}
catch (JsonProcessingException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
...
result
jsonGenerator
{"age":30,"name":"Hero","user":{"name":"Hero","age":30,"msgs":["msg1","msg2","msg3"]},"msg":["msg1","msg2","msg3"]}
objectMapper
{"age":30,"name":"Hero","user":{"name":"Hero","age":30,"msgs":["msg1","msg2","msg3"]},"msg":["msg1","msg2","msg3"]}
writeOthers2JSON
...
@Test
public void writeOthers2JSON()
{
try
{
String str = "hello world";
jsonGenerator.writeBinary(str.getBytes()); // byte
jsonGenerator.writeBoolean(true); // boolean
jsonGenerator.writeNull(); // null
jsonGenerator.writeNumber(8.8f); // float
jsonGenerator.writeRaw("c"); // char
jsonGenerator.writeRaw(str, 1, 6); // String
jsonGenerator.writeRawValue(str, 1, 6); // String
jsonGenerator.writeString(str); // String
jsonGenerator.writeTree(JsonNodeFactory.instance.POJONode(str));
System.out.println();
jsonGenerator.writeStartObject(); // {
jsonGenerator.writeObjectFieldStart("user"); // user:{
jsonGenerator.writeStringField("name", "Hero"); // name:Hero
jsonGenerator.writeNumberField("age", 30); // age:30
jsonGenerator.writeBooleanField("isMarried", true); // isMarried:true
jsonGenerator.writeEndObject(); // }
jsonGenerator.writeArrayFieldStart("infos"); // infos:[
jsonGenerator.writeNumber(8.8f); // 8.8
jsonGenerator.writeString("this is an array"); // this is an array
jsonGenerator.writeEndArray(); // ]
jsonGenerator.writeEndObject(); // }
String[] arrs = { "hello", "world", "Jackson" };
jsonGenerator.writeStartObject(); // {
jsonGenerator.writeObjectField("user", user); // user:{bean}
jsonGenerator.writeObjectField("infos", arrs); // infos:[array]
jsonGenerator.writeEndObject(); // }
}
catch (JsonGenerationException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
...
result
"aGVsbG8gd29ybGQ=" true null 8.8cello w ello w "hello world" "hello world"
{"user":{"name":"Hero","age":30,"isMarried":true},"infos":[8.8,"this is an array"]} {"user":{"name":"Hero","age":30,"msgs":["msg1","msg2","msg3"]},"infos":["hello","world","Jackson"]}
readJson2Entity
...
@Test
public void readJson2Entity()
{
try
{
User user = objectMapper.readValue(new File("Entity2Json.json"),
User.class);
System.out.println(user.getName());
System.out.println(user);
}
catch (JsonParseException e)
{
e.printStackTrace();
}
catch (JsonMappingException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
...
result
Hero
User[name=Hero,age=30,msgs=[msg1, msg2, msg3]]
readJson2List
...
@Test
public void readJson2List()
{
try
{
@SuppressWarnings("unchecked")
List<LinkedHashMap<String, Object>> list = objectMapper.readValue(
new File("List2Json.json"), List.class);
System.out.println(list.size());
for (LinkedHashMap<String, Object> map : list)
{
Set<Entry<String, Object>> set = map.entrySet();
for (Iterator<Entry<String, Object>> iterator = set.iterator(); iterator
.hasNext();)
{
Map.Entry<String, Object> entry = iterator.next();
String key = entry.getKey();
Object value = entry.getValue();
System.out.println(key + ":" + value);
}
}
}
catch (JsonParseException e)
{
e.printStackTrace();
}
catch (JsonMappingException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
...
result
1
name:Hero
age:30
msgs:[msg1, msg2, msg3]
readJson2Map
...
@Test
public void readJson2Map()
{
try
{
@SuppressWarnings("unchecked")
Map<String, Map<String, Object>> map = objectMapper.readValue(
new File("Map2Json.json"), Map.class);
System.out.println(map.size());
Set<String> set = map.keySet();
for (Iterator<String> iterator = set.iterator(); iterator.hasNext();)
{
String key = iterator.next();
Object value = map.get(key);
System.out.println(key + ":" + value);
}
}
catch (JsonParseException e)
{
e.printStackTrace();
}
catch (JsonMappingException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
...
result
4
age:30
name:Hero
user:{name=Hero, age=30, msgs=[msg1, msg2, msg3]}
msg:[msg1, msg2, msg3]
readJson2Array
...
@Test
public void readJson2Array()
{
try
{
User[] users = objectMapper.readValue(new File("List2Json.json"),
User[].class);
for (User user : users)
{
System.out.println(user);
}
}
catch (JsonParseException e)
{
e.printStackTrace();
}
catch (JsonMappingException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
...
result
User[name=Hero,age=30,msgs=[msg1, msg2, msg3]]