{ "name" : { "first" : "Joe", "last" : "Sixpack" }, "gender" : "MALE", "verified" : false, "userImage" : "Rm9vYmFyIQ==" }(2)Json转换成实体类:json2Entity()
/** * 将Json字符串转换成实体类 */ public static void json2Entity() { try { User user = mapper.readValue(new File("src/com/roctec/json/data.json"), User.class); System.out.println(user); } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }(3)实体类:User.java
package com.roctec.entity; import java.util.Arrays; 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; } @Override public String toString() { return "User [_gender=" + _gender + ", _name=[_first=" + _name._first + ", _last=" + _name._last + "], _isVerified=" + _isVerified + ", _userImage=" + Arrays.toString(_userImage) + "]"; } }(4)实体类转换成Json:entity2Json()
/** * 将实体类转换成Json字符串 */ public static void entity2Json() { User user = new User(); User.Name name = new User.Name(); name.setFirst("Joe"); name.setLast("Sixpack"); user.setName(name); user.setGender(User.Gender.MALE); user.setVerified(false); user.setUserImage("Rm9vYmFyIQ==".getBytes()); try { mapper.writeValue(new File("src/com/roctec/json/entity.json"), user); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
/** * 将Json字符串转换成map */ public static void json2Map() { try { @SuppressWarnings("unchecked") Map<String, Object> map = mapper.readValue(new File("src/com/roctec/json/data.json"), Map.class); for (Map.Entry<String, Object> entity : map.entrySet()) { System.out.println(entity.getKey() + "=" + entity.getValue()); } } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }(2)Map转换成Json:map2Json()
/** * 将map转换成Json字符串 */ public static void map2Json() { Map<String,Object> map = new HashMap<String,Object>(); Map<String,String> name = new HashMap<String,String>(); name.put("first", "Joe"); name.put("last", "Sixpack"); map.put("name", name); map.put("gender", "MALE"); map.put("verified", Boolean.FALSE); map.put("userImage", "Rm9vYmFyIQ=="); try { mapper.writeValue(new File("src/com/roctec/json/map.json"), map); } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
/** * 将Json字符串转换成树形 */ public static void json2Tree() { try { // 使用mapper.readTree(source),或使用mapper.readValue(source, JsonNode.class); JsonNode rootNode = mapper.readTree(new File("src/com/roctec/json/data.json")); // 确保"last name"不是"Xmler";如果是,就转换为"Jsoner" JsonNode nameNode = rootNode.path("name"); String lastName = nameNode.path("last").getTextValue(); if("xmler".equalsIgnoreCase(lastName)) { ((ObjectNode)nameNode).put("last", "Jsoner"); } mapper.writeValue(new File("src/com/roctec/json/tree.json"), rootNode); } catch (JsonProcessingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }(2)树形转换成Json:json2Tree()
/** * 将树形转换成Json字符串 */ public static void tree2Json() { ObjectNode rootNode = mapper.createObjectNode(); ObjectNode nameNode = rootNode.putObject("name"); nameNode.put("first", "Joe"); nameNode.put("last", "Sixpack"); rootNode.put("gender", User.Gender.MALE.toString()); rootNode.put("verified", false); byte[] imageBuf = "Rm9vYmFyIQ==".getBytes(); rootNode.put("userImage", imageBuf); try { mapper.writeValue(new File("src/com/roctec/json/tree.json"), rootNode); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
/** * 构造Json字符串 */ public static void generateJson() { try { JsonFactory factory = mapper.getJsonFactory(); JsonGenerator generator = factory.createJsonGenerator(new File("src/com/roctec/json/write.json"), JsonEncoding.UTF8); generator.writeStartObject(); generator.writeObjectFieldStart("name"); generator.writeStringField("first", "Joe"); generator.writeStringField("last", "Sixpack"); generator.writeEndObject(); generator.writeStringField("gender", User.Gender.MALE.toString()); generator.writeBooleanField("verified", false); generator.writeFieldName("userImage"); byte[] imageBuf = "Rm9vYmFyIQ==".getBytes(); generator.writeBinary(imageBuf); generator.writeEndObject(); generator.close(); } catch (IOException e) { e.printStackTrace(); } }(2)解析Json:parseJson()
/** * 解析Json字符串 */ public static void parseJson() { try { JsonFactory factory = mapper.getJsonFactory(); JsonParser parser = factory.createJsonParser(new File("src/com/roctec/json/data.json")); User user = new User(); parser.nextToken(); while(parser.nextToken() != JsonToken.END_OBJECT) { String fieldName = parser.getCurrentName(); parser.nextToken(); if("name".equals(fieldName)) { User.Name name = new User.Name(); while(parser.nextToken() != JsonToken.END_OBJECT) { String nameField = parser.getCurrentName(); parser.nextToken(); if("first".equals(nameField)) { name.setFirst(parser.getText()); } else if("last".equals(nameField)) { name.setLast(parser.getText()); } else { throw new IllegalStateException("Unrecognized field '" + fieldName + "'!"); } } user.setName(name); } else if("gender".equals(fieldName)) { user.setGender(User.Gender.valueOf(parser.getText())); } else if("verified".equals(fieldName)) { user.setVerified(parser.getCurrentToken() == JsonToken.VALUE_TRUE); } else if("userImage".equals(fieldName)) { user.setUserImage(parser.getBinaryValue()); } else { throw new IllegalStateException("Unrecognized field '" + fieldName + "'!"); } } parser.close(); System.out.println(user); } catch (JsonParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }(3)解析Json数组:parseJsonArray()
/** * 解析Json数组 */ public static void parseJsonArray() { String json = "[{\"foo\": \"bar\"}, {\"foo\": \"biz\"}]"; try { JsonFactory factory = mapper.getJsonFactory(); JsonParser parser = factory.createJsonParser(json); parser.nextToken(); while(parser.nextToken() == JsonToken.START_OBJECT) { Foo foo = mapper.readValue(parser, Foo.class); System.out.println(foo); } parser.close(); } catch (JsonParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }(4)实体类:Foo.java
package com.roctec.entity; public class Foo { public String foo; public String getFoo() { return foo; } public void setFoo(String foo) { this.foo = foo; } @Override public String toString() { return "Foo [foo=" + foo + "]"; } }
最后介绍一个窍门:可以通过JsonParser和JsonGenerator直接实现数据绑定和树型。请查看如下方法:
JsonParser.readValueAs()
JsonParser.readValueAsTree()
JsonGenerator.writeObject()
JsonGenerator.writeTree()
注意一点,确保使用的org.codehaus.jackson.map.MappingJsonFactory是“适用数据绑定”的解析器和生成器实例(而非基本的org.codehaus.jackson.JsonFactory)。