Android Json的使用(2) 使用Jackson解析和生成json
使用Jackson的三种方式
- 数据绑定模式:使用最方便
- 流模式:性能最佳
- 树模式:最灵活
以最常用的数据绑定模式为例
Json数据如下
- {
- "name" : { "first" : "Joe", "last" : "Sixpack" },
- "gender" : "MALE",
- "verified" : false,
- "userImage" : "Rm9vYmFyIQ=="
- }
json生成具体的java对象实例
- ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
- User user = mapper.readValue(new File("user.json"), User.class);
下面是User类:
- public class User {
- public enum Gender { MALE, FEMALE };
- public static class Name {
- private String _first, _last;
- public String getFirst() { return _first; }
- public String getLast() { return _last; }
- public void setFirst(String s) { _first = s; }
- public void setLast(String s) { _last = s; }
- }
- private Gender _gender;
- private Name _name;
- private boolean _isVerified;
- private byte[] _userImage;
- public Name getName() { return _name; }
- public boolean isVerified() { return _isVerified; }
- public Gender getGender() { return _gender; }
- public byte[] getUserImage() { return _userImage; }
- public void setName(Name n) { _name = n; }
- public void setVerified(boolean b) { _isVerified = b; }
- public void setGender(Gender g) { _gender = g; }
- public void setUserImage(byte[] b) { _userImage = b; }
从Java对象转换成Json
- mapper.writeValue(new File("user-modified.json"), user);
树模式例子
你还有另外一种方式来使用Jackson,就是使用树模式。这个就像XML的DOM树。Jackson用JsonNode来生成树。
如下所示:
- ObjectMapper m = new ObjectMapper();
- // can either use mapper.readTree(source), or mapper.readValue(source, JsonNode.class);
- JsonNode rootNode = m.readTree(new File("user.json"));
- // ensure that "last name" isn't "Xmler"; if is, change to "Jsoner"
- JsonNode nameNode = rootNode.path("name");
- String lastName = nameNode.path("last").getTextValue().
- if ("xmler".equalsIgnoreCase(lastName)) {
- ((ObjectNode)nameNode).put("last", "Jsoner");
- }
- // and write it out:
- m.writeValue(new File("user-modified.json"), rootNode);
你也可以自己构造一个树:
- TreeMapper treeMapper = new TreeMapper();
- ObjectNode userOb = treeMapper.objectNode();
- Object nameOb = userRoot.putObject("name");
- nameOb.put("first", "Joe");
- nameOb.put("last", "Sixpack");
- userOb.put("gender", User.Gender.MALE.toString());
- userOb.put("verified", false);
- byte[] imageData = getImageData(); // or wherever it comes from
- userOb.put("userImage", imageData);
流模式
这是最高效的模式。
生成json文本
- JsonFactory f = new JsonFactory();
- JsonGenerator g = f.createJsonGenerator(new File("user.json"));
- g.writeStartObject();
- g.writeObjectFieldStart("name");
- g.writeStringField("first", "Joe");
- g.writeStringField("last", "Sixpack");
- g.writeEndObject(); // for field 'name'
- g.writeStringField("gender", Gender.MALE);
- g.writeBooleanField("verified", false);
- g.writeFieldName("userImage"); // no 'writeBinaryField' (yet?)
- byte[] binaryData = ...;
- g.writeBinary(binaryData);
- g.writeEndObject();
- g.close(); // important: will force flushing of output, close underlying output stream
解析Json
- JsonFactory f = new JsonFactory();
- JsonParser jp = f.createJsonParser(new File("user.json"));
- User user = new User();
- jp.nextToken(); // will return JsonToken.START_OBJECT (verify?)
- while (jp.nextToken() != JsonToken.END_OBJECT) {
- String fieldname = jp.getCurrentName();
- jp.nextToken(); // move to value, or START_OBJECT/START_ARRAY
- if ("name".equals(fieldname)) { // contains an object
- Name name = new Name();
- while (jp.nextToken() != JsonToken.END_OBJECT) {
- String namefield = jp.getCurrentName();
- jp.nextToken(); // move to value
- if ("first".equals(namefield)) {
- name.setFirst(jp.getText());
- } else if ("last".equals(namefield)) {
- name.setLast(jp.getText());
- } else {
- throw new IllegalStateException("Unrecognized field '"+fieldname+"'!");
- }
- }
- user.setName(name);
- } else if ("gender".equals(fieldname)) {
- user.setGender(User.Gender.valueOf(jp.getText()));
- } else if ("verified".equals(fieldname)) {
- user.setVerified(jp.getCurrentToken() == JsonToken.VALUE_TRUE);
- } else if ("userImage".equals(fieldname)) {
- user.setUserImage(jp.getBinaryValue());
- } else {
- throw new IllegalStateException("Unrecognized field '"+fieldname+"'!");
- }
- }
- jp.close(); // ensure resources get cleaned up timely and properly
详细内容参见:http://wiki.fasterxml.com/JacksonInFiveMinutes
使用Jackson的三种方式
- 数据绑定模式:使用最方便
- 流模式:性能最佳
- 树模式:最灵活
以最常用的数据绑定模式为例
Json数据如下
- {
- "name" : { "first" : "Joe", "last" : "Sixpack" },
- "gender" : "MALE",
- "verified" : false,
- "userImage" : "Rm9vYmFyIQ=="
- }
json生成具体的java对象实例
- ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
- User user = mapper.readValue(new File("user.json"), User.class);
下面是User类:
- public class User {
- public enum Gender { MALE, FEMALE };
- public static class Name {
- private String _first, _last;
- public String getFirst() { return _first; }
- public String getLast() { return _last; }
- public void setFirst(String s) { _first = s; }
- public void setLast(String s) { _last = s; }
- }
- private Gender _gender;
- private Name _name;
- private boolean _isVerified;
- private byte[] _userImage;
- public Name getName() { return _name; }
- public boolean isVerified() { return _isVerified; }
- public Gender getGender() { return _gender; }
- public byte[] getUserImage() { return _userImage; }
- public void setName(Name n) { _name = n; }
- public void setVerified(boolean b) { _isVerified = b; }
- public void setGender(Gender g) { _gender = g; }
- public void setUserImage(byte[] b) { _userImage = b; }
从Java对象转换成Json
- mapper.writeValue(new File("user-modified.json"), user);
树模式例子
你还有另外一种方式来使用Jackson,就是使用树模式。这个就像XML的DOM树。Jackson用JsonNode来生成树。
如下所示:
- ObjectMapper m = new ObjectMapper();
- // can either use mapper.readTree(source), or mapper.readValue(source, JsonNode.class);
- JsonNode rootNode = m.readTree(new File("user.json"));
- // ensure that "last name" isn't "Xmler"; if is, change to "Jsoner"
- JsonNode nameNode = rootNode.path("name");
- String lastName = nameNode.path("last").getTextValue().
- if ("xmler".equalsIgnoreCase(lastName)) {
- ((ObjectNode)nameNode).put("last", "Jsoner");
- }
- // and write it out:
- m.writeValue(new File("user-modified.json"), rootNode);
你也可以自己构造一个树:
- TreeMapper treeMapper = new TreeMapper();
- ObjectNode userOb = treeMapper.objectNode();
- Object nameOb = userRoot.putObject("name");
- nameOb.put("first", "Joe");
- nameOb.put("last", "Sixpack");
- userOb.put("gender", User.Gender.MALE.toString());
- userOb.put("verified", false);
- byte[] imageData = getImageData(); // or wherever it comes from
- userOb.put("userImage", imageData);
流模式
这是最高效的模式。
生成json文本
- JsonFactory f = new JsonFactory();
- JsonGenerator g = f.createJsonGenerator(new File("user.json"));
- g.writeStartObject();
- g.writeObjectFieldStart("name");
- g.writeStringField("first", "Joe");
- g.writeStringField("last", "Sixpack");
- g.writeEndObject(); // for field 'name'
- g.writeStringField("gender", Gender.MALE);
- g.writeBooleanField("verified", false);
- g.writeFieldName("userImage"); // no 'writeBinaryField' (yet?)
- byte[] binaryData = ...;
- g.writeBinary(binaryData);
- g.writeEndObject();
- g.close(); // important: will force flushing of output, close underlying output stream
解析Json
- JsonFactory f = new JsonFactory();
- JsonParser jp = f.createJsonParser(new File("user.json"));
- User user = new User();
- jp.nextToken(); // will return JsonToken.START_OBJECT (verify?)
- while (jp.nextToken() != JsonToken.END_OBJECT) {
- String fieldname = jp.getCurrentName();
- jp.nextToken(); // move to value, or START_OBJECT/START_ARRAY
- if ("name".equals(fieldname)) { // contains an object
- Name name = new Name();
- while (jp.nextToken() != JsonToken.END_OBJECT) {
- String namefield = jp.getCurrentName();
- jp.nextToken(); // move to value
- if ("first".equals(namefield)) {
- name.setFirst(jp.getText());
- } else if ("last".equals(namefield)) {
- name.setLast(jp.getText());
- } else {
- throw new IllegalStateException("Unrecognized field '"+fieldname+"'!");
- }
- }
- user.setName(name);
- } else if ("gender".equals(fieldname)) {
- user.setGender(User.Gender.valueOf(jp.getText()));
- } else if ("verified".equals(fieldname)) {
- user.setVerified(jp.getCurrentToken() == JsonToken.VALUE_TRUE);
- } else if ("userImage".equals(fieldname)) {
- user.setUserImage(jp.getBinaryValue());
- } else {
- throw new IllegalStateException("Unrecognized field '"+fieldname+"'!");
- }
- }
- jp.close(); // ensure resources get cleaned up timely and properly
详细内容参见:http://wiki.fasterxml.com/JacksonInFiveMinutes
Android Json的使用(2) 使用Jackson解析和生成json的更多相关文章
- 运用 三种 原生 谷歌 阿里 解析和生成json
三种类生成JSON数据方法 JSON(原生): 第一种 JSONStringer和JSONObject区别在于添加对象时是按顺序添加的比如说 JSONStringer 添加 a:1 b:2 c:3那么 ...
- Json1:使用gson解析、生成json
Json解析: 1.json第三方解析包:json-lib.gson.jackson.fastjson等2.Google-gson只兼容jdk1.5版本以上:JSON-lib分别支持1.4和1.53. ...
- AJAX html 传输json字符串&&巧妙运用eval()来解析返回的JSON字符串
1.AJAX html 传输json字符串: js方法如下: function saveRetYwlsh(){ var xmbh = document.getElementById("xmb ...
- 使用gson解析,生成Json
包:gson-2.3.jarJson文本解析为Java对象:Java对象生成为Json文本 import com.google.gson.Gson; public class TestGson { c ...
- 使用JSONObject解析和生成json
创建JSON 引用org.json包,推荐通过maven引用 1.直接构建 JSONObject obj = new JSONObject(); obj.put("sex", &q ...
- Json4:使用json-lib解析、生成Json
特征:1.包多2.JSONObject.fromObject import net.sf.json.JSONObject; public class JsonLib { public static v ...
- 解决npm ERR!Unexpected end of JSON input while paring near (解析附近时JSON输入意外结束)'...."^2.0.0-rc.0","glob"'等npm install错误
摘要 最近更新了一次node,但是更新后npm的命令总是会报 npm WARN deprecated fsevents@2.0.6: Please update: there are crash fi ...
- [转] Android:用GSON 五招之内搞定任何JSON数组
[From] http://www.open-open.com/lib/view/open1472632967912.html 写在前面 关于GSON的入门级使用,这里就不提了,如有需要可以看这篇博文 ...
- 使用jsoncpp解析生成json
在此站点下载jsoncpp(https://sourceforge.net/projects/jsoncpp/这个站点的版本较旧) 在电脑上安装Python,运行amalgamate.py,生成的di ...
随机推荐
- windows访问linux共享文件夹
1.windows的网上邻居,是通过smb协议来共享信息的,如果需要给访问linux上的共享目录被windows访问到,需要linux有smb协议 sudo apt-get install samba ...
- EXT入门学习
今天,对EXT做了一下初步的了解,了解了一些基本用的函数.窗体对象.表单.文本域.按钮,一些基本的函数我列了出来,写了个登陆的demo,是根据别人的例子模仿出来的,见谅哈. 基本函数 Ext.onRe ...
- python的多线程、多进程代码示例
python多进程和多线程的区别:python的多线程不是真正意义上的多线程,由于python编译器的问题,导致python的多线程存在一个PIL锁,使得python的多线程的CPU利用率比预期的要低 ...
- mysql5.7 ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
mysql5.7初次登录使用提示 ERROR 1820 (HY000): You must reset your password using ALTER USER statement before ...
- LeetCode解题报告—— Reverse Linked List II & Restore IP Addresses & Unique Binary Search Trees II
1. Reverse Linked List II Reverse a linked list from position m to n. Do it in-place and in one-pass ...
- Nginx+PHP “No input file specified”错误的解决办法
配置官网商城php网站时候,界面报错“No input file specified” 原理: 任何对.php文件的请求,都简单地交给php-cgi去处理,但没有验证该php文件是否存在. PHP文件 ...
- STL模板整理 全排列
概念: 从n个不同元素中任取m(m≤n)个元素,按照一定的顺序排列起来,叫做从n个不同元素中取出m个元素的一个排列.当m=n时所有的排列情况叫全排列.如果这组数有n个,那么全排列数为n!个. 比如a, ...
- Pythonic和语法糖
Pythonic就是以Python的方式写出简洁优美的代码. 用Python独有的语法写Python语言. 知乎:https://www.zhihu.com/question/20244565 某博客 ...
- 洛谷——P1478 陶陶摘苹果(升级版)
题目描述 又是一年秋季时,陶陶家的苹果树结了n个果子.陶陶又跑去摘苹果,这次她有一个a公分的椅子.当他手够不着时,他会站到椅子上再试试. 这次与NOIp2005普及组第一题不同的是:陶陶之前搬凳子,力 ...
- sqlmap os shell解析
0x00 Background 最近遇到测试环境,最后利用sqlmap的--os-shell参数取得shell.一直以来,对这个参数的工作原理不是十分的清晰.大致的思想应该是将脚本插入到数据库中,然后 ...