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 ...
随机推荐
- python爬虫模块之数据存储模块
数据存储模块的话,目前我这用的比较多的是存储到mysql,所以下面的这个例子也是保存到mysql,用到了ORM映射的SQLAlchemy ,(ORM:Object-Relational Mapping ...
- sicily 1009. Mersenne Composite N
Description One of the world-wide cooperative computing tasks is the "Grand Internet Mersenne P ...
- Python简单的制作图片验证码
-人人可以学Python--这里示范的验证码都是简单的,你也可以把字符扭曲 人人可以学Python.png Python第三方库无比强大,PIL 是python的一个d第三方图片处理模块,我们也可以使 ...
- elasticsearch索引加别名
curl -XPOST 'http://localhost:9200/_aliases' -d ' { "actions": [ {&qu ...
- DataTable.DefaultView.Sort 排序方法
今天在整合一个东西,需要用到DataTable的一个排序方法, 前我是将DataTable存到DataView里面的,所以刚开始就使用了DataView.Sort="ColumnName A ...
- 论文笔记 《Maxout Networks》 && 《Network In Network》
论文笔记 <Maxout Networks> && <Network In Network> 发表于 2014-09-22 | 1条评论 出处 maxo ...
- 176. Second Highest Salary
Write a SQL query to get the second highest salary from the Employee table. +----+--------+ | Id | S ...
- hdu 5576 dp
题目大意:给你一个长度为 n 的 字符串表示一个乘法,一次操作随机选两个字符进行交换,进行m次操作,让你求出所有可能操作 的答案和. (1 <= n, m <= 50) 思路:巨难.. ...
- 35.Spark系统运行内幕机制循环流程
一:TaskScheduler原理解密 1, DAGScheduler在提交TaskSet给底层调度器的时候是面向接口TaskScheduler的,这符合面向对象中依赖抽象而不依赖的原则,带来底层资 ...
- cocos2dx三种定时器的使用以及停止schedule,scheduleUpdate,scheduleOnce。
今天白白跟大家分享一下cocos2dx中定时器的使用方法. 首先,什么是定时器呢?或许你有时候会想让某个函数不断的去执行,或许只是执行一次,获取你想让他每隔几秒执行一次,ok,这些都可以统统交给定时器 ...