在工作中实际使用到Java处理JSON的情况,且有很大部分都使用的是开源工具Jackson实现的。

一.入门

Jackson中有个ObjectMapper类很是实用,用于Java对象与JSON的互换。

1.Java对象转换为JSON

  1. Student st=new Student(); //Java Object
  2. ObjectMapper mapper = new ObjectMapper();
  3. java.text.DateFormat myFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  4. mapper.getSerializationConfig().setDateFormat(myFormat);
  5. try {
  6. //返回字符串
  7. String res = mapper.writeValueAsString(st);
  8. System.out.println(res);
  9. //输出格式化后的字符串(有性能损耗)
  10. res = mapper.defaultPrettyPrintingWriter().writeValueAsString(st);
  11. System.out.println(res);
  12. mapper.writeValue(new File("D:\\st.json"), st); //指定文件写入
  13. //设置序列化配置(全局),设置序列化时不输出空值.
  14. mapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);
  15. res = mapper.writeValueAsString(st);
  16. System.out.println(res);
  17. } catch (Exception e) {
  18. e.printStackTrace();
  19. }
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对象

  1. 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\":[]}}";
  2. ObjectMapper mapper = new ObjectMapper();
  3. //解析器支持解析单引号
  4. mapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
  5. //解析器支持解析结束符
  6. mapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
  7. try {
  8. //转换为HashMap对象
  9. HashMap jsonMap = mapper.readValue(json, HashMap.class);
  10. Map<String, Map<String, Object>> maps = objectMapper.readValue(json, Map.class);
  11. System.out.println(maps.get("error"));//0
  12. System.out.println((Object) (maps.get("data").get("phone")));//{home=abc, mobile=def}
  13. } catch (Exception e) {
  14. e.printStackTrace();
  15. }
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

  1. /*
  2. * Full Data Binding
  3. */
  4. public static void fullDataBinding() {
  5. ObjectMapper mapper = new ObjectMapper();
  6. try {
  7. Model model = mapper.readValue(MODEL_BINDING, Model.class);
  8. //readValue到一个实体类中.
  9. System.out.println(model.getName()); //name1
  10. System.out.println(model.getType()); //1
  11. } catch (Exception e) {
  12. e.printStackTrace();
  13. }
  14. }
  15. private static class Model {
  16. private String name;
  17. private int type;
  18. public String getName() {
  19. return name;
  20. }
  21. public void setName(String name) {
  22. this.name = name;
  23. }
  24. public int getType() {
  25. return type;
  26. }
  27. public void setType(int type) {
  28. this.type = type;
  29. }
  30. }
/*
* 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

  1. /*
  2. * Raw Data Binding
  3. */
  4. public static void rawDataBinding() {
  5. ObjectMapper mapper = new ObjectMapper();
  6. try {
  7. HashMap map = mapper.readValue(MODEL_BINDING, HashMap.class);//readValue到一个原始数据类型.
  8. System.out.println(map.get("name")); //name1
  9. System.out.println(map.get("type")); //1
  10. } catch (Exception e) {
  11. e.printStackTrace();
  12. }
  13. }
/*
* 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

  1. /*
  2. * generic Data Binding
  3. */
  4. public static void genericDataBinding() {
  5. ObjectMapper mapper = new ObjectMapper();
  6. try {
  7. HashMap<String, Model> modelMap = mapper.readValue(GENERIC_BINDING,
  8. new TypeReference<HashMap<String, Model>>() {
  9. });//readValue到一个范型数据中.
  10. Model model = modelMap.get("key2");
  11. System.out.println(model.getName()); //name3
  12. System.out.println(model.getType()); //3
  13. } catch (Exception e) {
  14. e.printStackTrace();
  15. }
  16. }
/*
* generic Data Binding
*/
public static void genericDataBinding() {
ObjectMapper mapper = new ObjectMapper();
try {
HashMap&lt;String, Model&gt; modelMap = mapper.readValue(GENERIC_BINDING,
new TypeReference&lt;HashMap&lt;String, Model&gt;&gt;() {
});//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:最灵活

  1. /*
  2. * Tree Model:最灵活
  3. */
  4. public static void treeModelBinding() {
  5. ObjectMapper mapper = new ObjectMapper();
  6. try {
  7. JsonNode rootNode = mapper.readTree(TREE_MODEL_BINDING);
  8. //path与get作用相同,但是当找不到该节点的时候,返回missing node而不是Null.
  9. String treekey2value = rootNode.path("treekey2").getTextValue();//
  10. System.out.println("treekey2value:" + treekey2value);
  11. JsonNode childrenNode = rootNode.path("children");
  12. String childkey1Value = childrenNode.get(0).path("childkey1").getTextValue();
  13. System.out.println("childkey1Value:" + childkey1Value);
  14. //创建根节点
  15. ObjectNode root = mapper.createObjectNode();
  16. //创建子节点1
  17. ObjectNode node1 = mapper.createObjectNode();
  18. node1.put("nodekey1", 1);
  19. node1.put("nodekey2", 2);
  20. //绑定子节点1
  21. root.put("child", node1);
  22. //数组节点
  23. ArrayNode arrayNode = mapper.createArrayNode();
  24. arrayNode.add(node1);
  25. arrayNode.add(1);
  26. //绑定数组节点
  27. root.put("arraynode", arrayNode);
  28. //JSON读到树节点
  29. JsonNode valueToTreeNode = mapper.valueToTree(TREE_MODEL_BINDING);
  30. //绑定JSON节点
  31. root.put("valuetotreenode", valueToTreeNode);
  32. //JSON绑定到JSON节点对象
  33. JsonNode bindJsonNode = mapper.readValue(GENERIC_BINDING, JsonNode.class);//绑定JSON到JSON节点对象.
  34. //绑定JSON节点
  35. root.put("bindJsonNode", bindJsonNode);
  36. System.out.println(mapper.writeValueAsString(root));
  37. } catch (Exception e) {
  38. e.printStackTrace();
  39. }
  40. }
/*
* 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字符串序列化。

文章来源:http://shensy.iteye.com/blog/1717776

最新文章

  1. 详细了解HTML标签内容模型
  2. 获取滚动条ScrollBar宽度
  3. 语音直播是否真能让国内网红向“Creator”转变?
  4. Codeforces Round #213 (Div. 2) A. Good Number
  5. 李洪强iOS开发之OC[011] - 有参方法的声明实现以及调用练习
  6. TFS2013 安装出现TF400102错误解决
  7. Windows脚本
  8. latin1字符集在navicat下显示乱码(mysql)
  9. ZFS+Dtrace+Zones+KVM=SMARTOS + dtrace 详细文档
  10. MySQL忘记密码解决办法
  11. redis可视化工具redisClient
  12. C++中模板template &lt;typename T&gt;
  13. python中的shutil模块
  14. C#嵌套类
  15. 使用dubbo中间件的zookeeper注册中心时报错
  16. Android 从浏览器启动应用
  17. MyBatis 实现新增
  18. Spark Strcutured Streaming中使用Dataset的groupBy agg 与 join 示例(java api)
  19. 《头文字D》热门同人插画欣赏
  20. UC浏览器调试移动端网站

热门文章

  1. ubuntu 14.04安装 nginx直播服务平台
  2. spark 的RDD各种转换和动作
  3. 与调试器共舞 - LLDB 的华尔兹
  4. JS中的事件、事件冒泡和事件捕获、事件委托
  5. python基础一 day10(2)
  6. js采用正则表达式获取地址栏参数
  7. Fortran学习笔记4(循环语句)
  8. 【线段树】uoj#228. 基础数据结构练习题
  9. 【Java_基础】java中的多态性
  10. GIMP语言设置