[url]http://jackson.codehaus.org/[/url]
lib:
jackson-core-asl-1.6.0.jar
jackson-mapper-asl-1.6.0.jar
[b]心得:最方便的是Full Data Binding 方式,不用额外处理,但是POJO的属性名需要与JSON的变量名一一对应。对于需要做JSON变量名和POJO属性名转换的话,使用Tree Model。[/b]
Jackson提供了三种方式处理JSON
[b]Streaming API[/b], 基于事件处理JSON,类似StAX API。性能最好,其它两种方法都是建立在它之上
[b]Tree Model[/b] 提供了内建文档树方式来展现JSON,类似XML DOM。最灵活。
[b]Data Binding[/b] 使用注释或者属性访问器JSON与POJOs之间转换。最方便。
以下是官方网站的例子
[b]1.Full Data Bindaing(POJO) Example[/b]
{
"name" : { "first" : "Joe", "last" : "Sixpack" },
"gender" : "MALE",
"verified" : false,
"userImage" : "Rm9vYmFyIQ=="
}
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;
}
}
ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
User user = mapper.readValue(new File("user.json"), User.class);
mapper.writeValue(new File("user-modified.json"), user);
2.Simple Data Binding Example
Map<String, Object> userData = mapper.readValue(new File("user.json"), Map.class);
userData = new HashMap<String, Object>();
Map<String, String> nameStruct = new HashMap<String, String>();
nameStruct.put("first", "Joe");
nameStruct.put("last", "Sixpack");
userData.put("name", nameStruct);
userData.put("gender", "MALE");
userData.put("verified", Boolean.FALSE);
userData.put("userImage", "Rm9vYmFyIQ==");
mapper.writeValue(new File("user-modified.json"), userData);
Concrete Java types that Jackson will use for simple data binding are:
[table]
|JSON Type | Java Type |
|object | LinkedHashMap<String,Object> |
|array | ArrayList<Object> |
|string | String |
|number (no fraction) | Integer, Long or BigInteger (smallest applicable) |
|number (fraction) | Double (configurable to use BigDecimal) |
|true false | Boolean |
|null | null |
[/table]
[b]3.The Model Example[/b]
ObjectMapper m = new ObjectMapper();
// can either use mapper.readTree(JsonParser), or bind to JsonNode
JsonNode rootNode = m.readValue(new File("user.json"), JsonNode.class);
// 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);