使用Jackson在Java中处理JSON
在工作中实际使用到Java处理JSON的情况,且有很大部分都使用的是开源工具Jackson实现的。
一.入门
Jackson中有个ObjectMapper类很是实用,用于Java对象与JSON的互换。
1.Java对象转换为JSON
- Student st=new Student(); //Java Object
- ObjectMapper mapper = new ObjectMapper();
- java.text.DateFormat myFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- mapper.getSerializationConfig().setDateFormat(myFormat);
- try {
- //返回字符串
- String res = mapper.writeValueAsString(st);
- System.out.println(res);
- //输出格式化后的字符串(有性能损耗)
- res = mapper.defaultPrettyPrintingWriter().writeValueAsString(st);
- System.out.println(res);
- mapper.writeValue(new File("D:\\st.json"), st); //指定文件写入
- //设置序列化配置(全局),设置序列化时不输出空值.
- mapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);
- res = mapper.writeValueAsString(st);
- System.out.println(res);
- } catch (Exception e) {
- e.printStackTrace();
- }
Student st=new Student(); //Java Object
ObjectMapper mapper = new ObjectMapper();
java.text.DateFormat myFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
mapper.getSerializationConfig().setDateFormat(myFormat);
try {
//返回字符串
String res = mapper.writeValueAsString(st);
System.out.println(res);//输出格式化后的字符串(有性能损耗)
res = mapper.defaultPrettyPrintingWriter().writeValueAsString(st);
System.out.println(res); mapper.writeValue(new File("D:\\st.json"), st); //指定文件写入 //设置序列化配置(全局),设置序列化时不输出空值.
mapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL); res = mapper.writeValueAsString(st);
System.out.println(res);
} catch (Exception e) {
e.printStackTrace();
}
2.JSON反序列化为Java对象
- String json = "{\"error\":0,\"data\":{\"name\":\"ABC\",\"age\":20,\"phone\":{\"home\":\"abc\",\"mobile\":\"def\"},\"friends\":[{\"name\":\"DEF\",\"phone\":{\"home\":\"hij\",\"mobile\":\"klm\"}},{\"name\":\"GHI\",\"phone\":{\"home\":\"nop\",\"mobile\":\"qrs\"}}]},\"other\":{\"nickname\":[]}}";
- ObjectMapper mapper = new ObjectMapper();
- //解析器支持解析单引号
- mapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
- //解析器支持解析结束符
- mapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
- try {
- //转换为HashMap对象
- HashMap jsonMap = mapper.readValue(json, HashMap.class);
- Map<String, Map<String, Object>> maps = objectMapper.readValue(json, Map.class);
- System.out.println(maps.get("error"));//0
- System.out.println((Object) (maps.get("data").get("phone")));//{home=abc, mobile=def}
- } catch (Exception e) {
- e.printStackTrace();
- }
String json = "{\"error\":0,\"data\":{\"name\":\"ABC\",\"age\":20,\"phone\":{\"home\":\"abc\",\"mobile\":\"def\"},\"friends\":[{\"name\":\"DEF\",\"phone\":{\"home\":\"hij\",\"mobile\":\"klm\"}},{\"name\":\"GHI\",\"phone\":{\"home\":\"nop\",\"mobile\":\"qrs\"}}]},\"other\":{\"nickname\":[]}}";
ObjectMapper mapper = new ObjectMapper();
//解析器支持解析单引号
mapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
//解析器支持解析结束符
mapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
try {
//转换为HashMap对象
HashMap jsonMap = mapper.readValue(json, HashMap.class);
Map<String, Map<String, Object>> maps = objectMapper.readValue(json, Map.class);
System.out.println(maps.get("error"));//0
System.out.println((Object) (maps.get("data").get("phone")));//{home=abc, mobile=def}
} catch (Exception e) {
e.printStackTrace();
}
二.Jackson支持三种使用方式
1.Data Binding:最方便使用
(1)Full Data Binding
- /*
- * Full Data Binding
- */
- public static void fullDataBinding() {
- ObjectMapper mapper = new ObjectMapper();
- try {
- Model model = mapper.readValue(MODEL_BINDING, Model.class);
- //readValue到一个实体类中.
- System.out.println(model.getName()); //name1
- System.out.println(model.getType()); //1
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- private static class Model {
- private String name;
- private int type;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getType() {
- return type;
- }
- public void setType(int type) {
- this.type = type;
- }
- }
/*
* Full Data Binding
*/
public static void fullDataBinding() {ObjectMapper mapper = new ObjectMapper();
try {
Model model = mapper.readValue(MODEL_BINDING, Model.class);
//readValue到一个实体类中.
System.out.println(model.getName()); //name1
System.out.println(model.getType()); //1
} catch (Exception e) {
e.printStackTrace();
}
}
private static class Model {
private String name;
private int type;public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getType() {
return type;
} public void setType(int type) {
this.type = type;
}
}
(2)Raw Data Binding
- /*
- * Raw Data Binding
- */
- public static void rawDataBinding() {
- ObjectMapper mapper = new ObjectMapper();
- try {
- HashMap map = mapper.readValue(MODEL_BINDING, HashMap.class);//readValue到一个原始数据类型.
- System.out.println(map.get("name")); //name1
- System.out.println(map.get("type")); //1
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
/*
* Raw Data Binding
*/
public static void rawDataBinding() {
ObjectMapper mapper = new ObjectMapper();
try {
HashMap map = mapper.readValue(MODEL_BINDING, HashMap.class);//readValue到一个原始数据类型.
System.out.println(map.get("name")); //name1
System.out.println(map.get("type")); //1
} catch (Exception e) {
e.printStackTrace();
}
}
(3)generic Data Binding
- /*
- * generic Data Binding
- */
- public static void genericDataBinding() {
- ObjectMapper mapper = new ObjectMapper();
- try {
- HashMap<String, Model> modelMap = mapper.readValue(GENERIC_BINDING,
- new TypeReference<HashMap<String, Model>>() {
- });//readValue到一个范型数据中.
- Model model = modelMap.get("key2");
- System.out.println(model.getName()); //name3
- System.out.println(model.getType()); //3
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
/*
* generic Data Binding
*/
public static void genericDataBinding() {ObjectMapper mapper = new ObjectMapper();
try {
HashMap<String, Model> modelMap = mapper.readValue(GENERIC_BINDING,
new TypeReference<HashMap<String, Model>>() {
});//readValue到一个范型数据中.
Model model = modelMap.get("key2");
System.out.println(model.getName()); //name3
System.out.println(model.getType()); //3
} catch (Exception e) {
e.printStackTrace();
}
}
2.Tree Model:最灵活
- /*
- * Tree Model:最灵活
- */
- public static void treeModelBinding() {
- ObjectMapper mapper = new ObjectMapper();
- try {
- JsonNode rootNode = mapper.readTree(TREE_MODEL_BINDING);
- //path与get作用相同,但是当找不到该节点的时候,返回missing node而不是Null.
- String treekey2value = rootNode.path("treekey2").getTextValue();//
- System.out.println("treekey2value:" + treekey2value);
- JsonNode childrenNode = rootNode.path("children");
- String childkey1Value = childrenNode.get(0).path("childkey1").getTextValue();
- System.out.println("childkey1Value:" + childkey1Value);
- //创建根节点
- ObjectNode root = mapper.createObjectNode();
- //创建子节点1
- ObjectNode node1 = mapper.createObjectNode();
- node1.put("nodekey1", 1);
- node1.put("nodekey2", 2);
- //绑定子节点1
- root.put("child", node1);
- //数组节点
- ArrayNode arrayNode = mapper.createArrayNode();
- arrayNode.add(node1);
- arrayNode.add(1);
- //绑定数组节点
- root.put("arraynode", arrayNode);
- //JSON读到树节点
- JsonNode valueToTreeNode = mapper.valueToTree(TREE_MODEL_BINDING);
- //绑定JSON节点
- root.put("valuetotreenode", valueToTreeNode);
- //JSON绑定到JSON节点对象
- JsonNode bindJsonNode = mapper.readValue(GENERIC_BINDING, JsonNode.class);//绑定JSON到JSON节点对象.
- //绑定JSON节点
- root.put("bindJsonNode", bindJsonNode);
- System.out.println(mapper.writeValueAsString(root));
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
/*
* Tree Model:最灵活
*/
public static void treeModelBinding() {
ObjectMapper mapper = new ObjectMapper();
try {
JsonNode rootNode = mapper.readTree(TREE_MODEL_BINDING);
//path与get作用相同,但是当找不到该节点的时候,返回missing node而不是Null.
String treekey2value = rootNode.path("treekey2").getTextValue();//
System.out.println("treekey2value:" + treekey2value);
JsonNode childrenNode = rootNode.path("children");
String childkey1Value = childrenNode.get(0).path("childkey1").getTextValue();
System.out.println("childkey1Value:" + childkey1Value);//创建根节点
ObjectNode root = mapper.createObjectNode();
//创建子节点1
ObjectNode node1 = mapper.createObjectNode();
node1.put("nodekey1", 1);
node1.put("nodekey2", 2);
//绑定子节点1
root.put("child", node1);
//数组节点
ArrayNode arrayNode = mapper.createArrayNode();
arrayNode.add(node1);
arrayNode.add(1);
//绑定数组节点
root.put("arraynode", arrayNode);
//JSON读到树节点
JsonNode valueToTreeNode = mapper.valueToTree(TREE_MODEL_BINDING);
//绑定JSON节点
root.put("valuetotreenode", valueToTreeNode);
//JSON绑定到JSON节点对象
JsonNode bindJsonNode = mapper.readValue(GENERIC_BINDING, JsonNode.class);//绑定JSON到JSON节点对象.
//绑定JSON节点
root.put("bindJsonNode", bindJsonNode);
System.out.println(mapper.writeValueAsString(root));
} catch (Exception e) {
e.printStackTrace();
}
}
3.Streaming API。最佳性能
见官方文档例子。
进一步学习资料:
1.http://wiki.fasterxml.com/JacksonInFiveMinutes Jackson官方教程示例
2.http://wiki.fasterxml.com/JacksonJavaDocs Jackson在线API文档
3.http://hjg1988.iteye.com/blog/561368 JSON工具性能比较:json-lib和jackson进行Java对象到json字符串序列化。
使用Jackson在Java中处理JSON的更多相关文章
- JSON(三)——java中对于JSON格式数据的解析之json-lib与jackson
java中对于JSON格式数据的操作,主要是json格式字符串与JavaBean之间的相互转换.java中能够解析JSON格式数据的框架有很多,比如json-lib,jackson,阿里巴巴的fast ...
- Java中哪个JSON库的解析速度是最快的?
JSON已经成为当前服务器与WEB应用之间数据传输的公认标准,不过正如许多我们所习以为常的事情一样,你会觉得这是理所当然的便不再深入思考 了.我们很少会去想用到的这些JSON库到底有什么不同,但事实上 ...
- JAVA中使用JSON进行数据传递
最近在做一个基于JAVA Servlet的WEB应用以及对应的Anroid应用客户端的开发工作. 其中,在接口的访问和数据的传输方面使用的比较多的是使用JSON对象来操作格式化数据:在服务器端采用JS ...
- 转载:JAVA中使用JSON进行数据传递
转载网址:http://www.cnblogs.com/undead/archive/2012/07/18/2594900.html 最近在做一个基于JAVA Servlet的WEB应用以及对应的An ...
- 3、示例(在java中使用JSON)
教程链接(json-smple1.1.1.jar文件) 链接:http://pan.baidu.com/s/1qXPbYHm 密码:v0f0 如何使用java编程语言编码和解码JSON 首先准备环境以 ...
- Java中的Json序列化,不容忽视的getter
在开发的过程中,经常会碰到和自己预期不一样的情况.有的时候自己去研究一下还是很有趣的.这两天在写java web的时候,碰到了一个对象序列化的问题. 问题重现 public class AjaxJso ...
- JackSon将java对象转换为JSON字符串
JackSon可以将java对象转换为JSON字符串,步骤如下: 1.导入JackSon 的jar包 2.创建ObjectMapper对象 3.使用ObjectMapper对象的writeValueA ...
- (后端)JackSon将java对象转换为JSON字符串(转)
转载小金金金丶园友: JackSon可以将java对象转换为JSON字符串,步骤如下: 1.导入JackSon 的jar包 2.创建ObjectMapper对象 3.使用ObjectMapper对象的 ...
- Java 中的JSON 字符串
类库选择 Java中并没有内置JSON的解析,因此使用JSON需要借助第三方类库. 下面是几个常用的 JSON 解析类库: Gson: 谷歌开发的 JSON 库,功能十分全面. FastJson: 阿 ...
随机推荐
- fun下载内容批量收集
1.download title and url #!/usr/bin/env python #-*- coding:utf-8 -*- import re, urllib2,threading de ...
- UVA1660 Cable TV Network (无向图的点连通度)
题意:求一个无向图的点连通度. 把一个点拆成一个入点和一个出点,之间连一条容量为1的有向边,表示能被用一次.最大流求最小割即可. 一些细节的东西:1.源点固定,汇点要枚举一遍,因为最小割割断以后会形成 ...
- C02 信息存储与运算
目录 计算机内存 常量和变量 数据类型 运算符 计算机内存管理 计算机内存 信息存储概述 使用程序进行开发时,需要存储各种信息,这时候就需要用到变量.由于信息类型不同,变量的类型也因此不尽相同. 同时 ...
- tomcat中如何禁止和允许主机或地址访问
1.tomcat中如何禁止和允许列目录下的文件 在{tomcat_home}/conf/web.xml中,把listings参数设置成false即可,如下: <servlet>...< ...
- GloVe:另一种Word Embedding方法
若想深层地理解GloVe和本文,最好了解SVD, word2vec(skip-gram为主)的相关知识.若仅寻求一种新的word embedding方法,可以不必了解以上前置知识. 一言以蔽之,Glo ...
- HDU - 4811 - Ball (思维)
题意: 给出一定数量的三种颜色的球,计算如何摆放得到值最大(有一定顺序) 有三种摆放方法 1.如果放的是第一个(桌子上原来没有),数值不变 2.如果在末尾追加一个,那么增加前面不同颜色的个数的值 3. ...
- python中函数定义之实参、形参
一般在函数的定义中,会有一类变量---形参,它是函数完成其工作的一项信息.实参往往是调用函数时传递给函数的信息.我们在调用函数时,将要让函数使用的信息放在括号内.例如定义一个函数def greet_u ...
- cache支持三种pre-fetch方式:normal/pre-fetch1/pre-fetch2-way1/pre-fetch-way2
1.normal fetch ----fetch 1 cache line once 2. pre-fetch mode one ---- fetch 3 cache line once 3.pre ...
- android sdk 下载
不知道是因为最近kaihui还是怎么的,打开android sdk官方网站特别的慢,想下载最新版本的platform几乎变成不可能完成的任务,不知道为什么Google不像Apache那样在各国设立镜像 ...
- WCF全局异常处理
在用wcf做为单纯的服务端的时候,发生错误是常有的事情,特别是在调用其他系统提供的接口的时候,发生的一些错误总是让人摸不着头脑,严重影响了错误的定位.做.net web开发的时候,我们可以在Globa ...