Jackson 是一般比较常用的JSON解析框架, Spring mvc 中就是用Jackson解析JSON的.
官方网址: https://github.com/FasterXML/jackson
需要注意 Jackson 有两个版本,1.X 版已经是废弃状态. 新版的是2.X . 本系列文章基于Jackson 2 讲解
Java Bean 到 JSON
要想把Java Bean 转换为 JSON 字符串,可以直接用下面代码:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);// 格式化输出
String result = mapper.writeValueAsString(bean);
大多数情况下,上面代码就足以完成任务了.
格式化日期
如果有日期字段,可以用下面代码格式化
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
mapper.setDateFormat(format); //格式化日期
重命名字段
默认使用字段名作为JSON中属性名,可以通过 mapper.setPropertyNamingStrategy()
定制不同的名称转换策略
* PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES
* PropertyNamingStrategy.LOWER_CASE
* PropertyNamingStrategy.PASCAL_CASE_TO_CAMEL_CASE
或者自定义实现
mapper.setPropertyNamingStrategy(new PropertyNamingStrategy() {
@Override
public String nameForField(MapperConfig<?> config, AnnotatedField field, String defaultName) {
if(field.getFullName().equals("com.yln.jackson.pojo.Artist#name"))
return "Artist-Name";
return super.nameForField(config, field, defaultName);
}
@Override
public String nameForGetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName) {
if(method.getDeclaringClass().equals(Album.class) && defaultName.equals("title")){
return "Album-Title";
}
return super.nameForGetterMethod(config, method, defaultName);
}
});
不输出NULL
mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
直接生成JSON
有时我们不想为了生成一个JSON串,创建一堆类文件.可以直接生成JSON字符串
public class JacksonV2Tree2Json {
public static void main(String[] args) throws IOException {
JsonFactory jsonFactory = new JsonFactory();
JsonGenerator generator = jsonFactory.createGenerator(System.out);
ObjectMapper mapper = new ObjectMapper();
JsonNodeFactory factory = new JsonNodeFactory(false);
ObjectNode album = factory.objectNode();
album.put("Album-Title", "Kind Of Blue");
ArrayNode links = factory.arrayNode();
links.add("link1").add("link1");
album.put("links",links);
ObjectNode artist = factory.objectNode();
artist.put("Artist-Name", "Miles Davis");
artist.put("birthDate", "26 May 1926");
album.put("artist", artist);
ObjectNode musicians = factory.objectNode();
musicians.put("Julian Adderley", "Alto Saxophone");
musicians.put("Miles Davis", "Trumpet, Band leader");
album.put("musicians", musicians);
mapper.writeTree(generator,album);
}
}