使用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
使用Jackson的三种方式
- 数据绑定模式:使用最方便
- 流模式:性能最佳
- 树模式:最灵活
以最常用的数据绑定模式为例
Json数据如下
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
树模式例子
你还有另外一种方式来使用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