在解析JSON方面,无疑JACKSON是做的最好的,下面从几个方面简单复习下。
1 JAVA 对象转为JSON
import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class JacksonExample {
public static void main(String[] args) {
User user = new User();
ObjectMapper mapper = new ObjectMapper();
try {
// convert user object to json string, and save to a file
mapper.writeValue(new File("c:\\user.json"), user);
// display to console
System.out.println(mapper.writeValueAsString(user));
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
输出为:
{"age":29,"messages":["msg 1","msg 2","msg 3"],"name":"mkyong"}
2 JSON反序列化为JAVA对象
import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class JacksonExample {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
try {
// read from file, convert it to user class
User user = mapper.readValue(new File("c:\\user.json"), User.class);
// display to console
System.out.println(user);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
输出:User [age=29, name=mkyong, messages=[msg 1, msg 2, msg 3]]
3 在上面的例子中,如果要输出的JSON好看点,还是有办法的,就是使用
defaultPrettyPrintingWriter()方法,例子为:
User user = new User();
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.defaultPrettyPrintingWriter().writeValueAsString(user));
则输出整齐:
{
"age" : 29,
"messages" : [ "msg 1", "msg 2", "msg 3" ],
"name" : "mkyong"
}