原文连接:http://www.dubby.cn/detail.html?id=9070html
前几篇介绍Jackson的文章(Jackson介绍,Jackson之jackson-core),虽然很好,可是我相信你并愿意在项目中使用,由于使用起来很复杂,也许这也是不少人愿意使用Fastjson的缘由吧。为何会感受这么复杂呢,由于jackson-core提供的是很低级的API,咱们能够充分的了解细节,可是代价就是操做起来更复杂。json
这篇文章介绍使用高级的API,让你看到Jackson也能够这么的简单,容易。api
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.2</version>
</dependency>
复制代码
由于jackson-databind依赖core和annotations,因此在这里须要依赖这三个jar。bash
给出一个足够简单的POJO:app
public class MyValue {
public String name;
public int age;
}
复制代码
注意:若是使用getters/setters的话,能够用private/protected修饰属性,这里直接用public修饰了,就不须要getters/setters了。工具
使用databind
,咱们须要一个最基础的对象com.fasterxml.jackson.databind.ObjectMapper
,这里咱们构造一个:性能
ObjectMapper mapper = new ObjectMapper();
复制代码
注意:这个mapper是能够复用的,就比如HttpClient同样。ui
简单的把JSON反序列化成Object的用法以下:this
MyValue value = mapper.readValue(new File("data.json"), MyValue.class);
// or:
value = mapper.readValue(new URL("http://www.dubby.cn/api/entry.json"), MyValue.class);
// or:
value = mapper.readValue("{\"name\":\"Bob\", \"age\":13}", MyValue.class);
复制代码
简单的把Object序列化成JSON的用法以下:编码
mapper.writeValue(new File("result.json"), myResultObject);
// or:
byte[] jsonBytes = mapper.writeValueAsBytes(myResultObject);
// or:
String jsonString = mapper.writeValueAsString(myResultObject);
复制代码
其实到这一步,对于不少读者来讲已经足够了。由于大部分时候咱们要的就是这些。可是不妨继续看下去,还有一些你可能会用到的。
若是你使用的不是简单的POJO,而是List
,Map
:
Map<String, Integer> scoreByName = mapper.readValue(jsonSource, Map.class);
List<String> names = mapper.readValue(jsonSource, List.class);
mapper.writeValue(new File("names.json"), names);
复制代码
若是你反序列化的更复杂,你能够指定类型:
Map<String, ResultValue> results = mapper.readValue(jsonSource, new TypeReference<Map<String, ResultValue>>() { } );
复制代码
思考:为何须要指定类型?(类型擦除)
注意:序列化的时候不须要指定,只有反序列化的时候须要。
虽然看起来处理的很方便,可是某些时候会有一些很麻烦的状况,这时候能够考虑使用树模型:
//若是结果多是Object或者是Array,那能够使用JsonNode;
//若是你知道是Object,你能够直接强转成ObjectNode;若是你知道是Array,你能够直接强转成ArrayNode;
ObjectNode root = (ObjectNode) mapper.readTree("stuff.json");
String name = root.get("name").asText();
int age = root.get("age").asInt();
// 还能够修改这个树,而后再输出成json字符串
root.with("other").put("type", "student");
String json = mapper.writeValueAsString(root);
// with above, we end up with something like as 'json' String:
// {
// "name" : "Bob", "age" : 13,
// "other" : {
// "type" : "student"
// }
// }
复制代码
上面的例子中的JSON以下:
{
"name" : "Bob", "age" : 13,
"other" : {
"type" : "student"
}
}
复制代码
若是 json 类型太过动态,不适合反序列化成对象的时候,树模型比数据绑定更合适。
看完上面的介绍,我想你应该至关满意ObjectMapper
的能力了,可是若是你但愿控制底层的一些细节,或者对性能有更高的要求,你能够经过ObjectMapper
来设置。建议你先看看Jackson之jackson-core:
JsonFactory f = mapper.getFactory();
// 一、输入JSON字符串
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
JsonGenerator g = f.createGenerator(outputStream);
// 输出JSON: { "message" : "Hello world!" }
g.writeStartObject();
g.writeStringField("message", "Hello world!");
g.writeEndObject();
g.close();
// 二、把JSON字符串反序列化
JsonParser p = f.createParser(outputStream.toString());
JsonToken t = p.nextToken(); // Should be JsonToken.START_OBJECT
t = p.nextToken(); // JsonToken.FIELD_NAME
if ((t != JsonToken.FIELD_NAME) || !"message".equals(p.getCurrentName())) {
// handle error
}
t = p.nextToken();
if (t != JsonToken.VALUE_STRING) {
// similarly
}
String msg = p.getText();
System.out.printf("My message to you is: %s!\n", msg);
p.close();
复制代码
你也能够直接构造
JsonFactory
,而后做为构造参数传给ObjectMapper
。
有两个方面的配置,特性和注解。
给出一个简单的使用特性配置的例子,先给出序列化配置:
// 设置序列化成漂亮的JSON,而不是压缩的字符串
mapper.enable(SerializationFeature.INDENT_OUTPUT);
// 若是你要序列化的对象没有字段(很搞笑吧),会抛异常,能够设置这个来避免异常,直接序列化成`{}`
mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
// 默认Date会序列化成时间戳,能够设置这个来序列化成`date":"2017-12-09T12:50:13.000+0000`这个样子
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
复制代码
反序列化配置的例子:
// 默认,若是反序列化时,JSON字符串里有字段,而POJO中没有定义,会抛异常,能够设置这个来忽略未定义的字段
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
// 默认若是是字符串(""),反序列化会失败,能够开启这个设置,字符串("")会被反序列化成(null)
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
复制代码
除此以外,还能够针对序列化和反序列化的底层细节指定一些配置,先给出parsing的配置:
// 默认若是JSON中有C/C++风格的注释,在反序列化的时候会报错,能够指定这个配置来忽略C/C++风格的注释
mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
//默认JSON字符串若是字段名没有用双引号包裹,回报错,能够设置这个来支持这种非正规的JSON(JS支持这种非正规的JSON)
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
// 默认若是JSON中是用的单引号包裹字段和值,反序列化时会报错,能够设置这个来兼容单引号这种非正规的JSON
mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
复制代码
再给出generation的配置:
// 把非ASCII转义成ASCII值,如(杨正)会被转义成(\u6768\u6B63)
mapper.configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true);
复制代码
注解@JsonProperty
:
public class MyBean {
private String _name;
// 默认是`theName`,如今改成`name`
@JsonProperty("name")
public String getTheName() { return _name; }
// 只须要修饰getter或者setter其中的一个就能够了,这里能够省略不写
public void setTheName(String n) { _name = n; }
}
复制代码
@JsonIgnore
能够忽略单个字段,@JsonIgnoreProperties
能够加在类定义上:
// 序列化和反序列化时,直接忽略JSON中的foo和bar字段
@JsonIgnoreProperties({ "foo", "bar" })
public class MyBean
{
// 序列化和反序列化时,直接忽略JSON中的internal字段
@JsonIgnore
public String internal;
// 正常字段
public String external;
@JsonIgnore
public void setCode(int c) { _code = c; }
// 虽然这里没有修饰,可是setter被修饰了,因此也会被忽略
public int getCode() { return _code; }
}
复制代码
从上面咱们能够看出,注解在字段名、setter和getter上都是同样的,修饰任何一个都会直接忽略这个字段,可是咱们能够值忽略反序列化,而不忽略序列化,或者反之:
public class ReadButDontWriteProps {
private String _name;
@JsonProperty public void setName(String n) { _name = n; }
@JsonIgnore public String getName() { return _name; }
}
复制代码
这里使用@JsonProperty
保证,虽然序列化是name会被忽略,可是从JSON中反序列化时,能够正常接收这个字段。
和其余数据绑定工具不同,Jackson不会强制要求你的POJO必须有个默认构造方法(无参构造方法)。你能够指定一个构造方法来接收反序列化的字段值:
public class CtorBean
{
public final String name;
public final int age;
@JsonCreator
private CtorBean(@JsonProperty("name") String name,
@JsonProperty("age") int age)
{
this.name = name;
this.age = age;
}
}
复制代码
构造方法能够是public,private或者任何其余修饰符修饰
对于一些不可改变的对象,这个会颇有用,除了构造方法,@JsonCreator
这个注解还能够定义一个工厂方法:
public class FactoryBean
{
// fields etc omitted for brewity
@JsonCreator
public static FactoryBean create(@JsonProperty("name") String name) {
// construct and return an instance
}
}
复制代码
注意:构造方法(@JsonCreator
和@JsonProperty
)和setter不互斥,你能够混合使用。
Jackson还有一个颇有意思的功能,虽然没有普遍的被人所知道。那就是POJO和POJO之间的转换。概念性的能够理解成POJO1->JSON->POJO2,可是实际上会省略中间这一步,不会真正的生成JSON,而会用其余更高效的实现:
ResultType result = mapper.convertValue(sourceObject, ResultType.class);
复制代码
还有其余用法:
// List<Integer> -> int[]
List<Integer> sourceList = ...;
int[] ints = mapper.convertValue(sourceList, int[].class);
// POJO -> Map
Map<String,Object> propertyMap = mapper.convertValue(pojoValue, Map.class);
// Map -> POJO
PojoType pojo = mapper.convertValue(propertyMap, PojoType.class);
// decode Base64! (default byte[] representation is base64-encoded String)
复制代码
甚至还能够解码base64码:
//解码
String base64 = "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz";
byte[] binary = mapper.convertValue(base64, byte[].class);
System.out.println(new String(binary));
//编码
String str = "Man is distinguished, not only by his reason, but by this";
String base = mapper.convertValue(str.getBytes(), String.class);
System.out.println(base);
复制代码
因此,Jackson甚至强大到能够代替Apache Commons组件。