In terms of JSON parsing, JACKSON is undoubtedly the best, and the following is a brief review of several aspects.
1. Convert the JAVA object to JSON
Java code
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 ();
}
}
Output:
{"Age": 29, "messages": ["msg 1", "msg 2", "msg 3"], "name": "mkyong "}
2 JSON deserialization into a JAVA object
Java code
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 ();
}
}
Output: User [age = 29, name = mkyong, messages = [msg 1, msg 2, msg 3]
3 In the above example, if the JSON to be output is nice, there is still a way to use
DefaultPrettyPrintingWriter () method, for example:
Java code
User user = new User ();
ObjectMapper mapper = new ObjectMapper ();
System. out. println (mapper. defaultPrettyPrintingWriter (). writeValueAsString (user ));
The output is neat:
{
"Age": 29,
"Messages": ["msg 1", "msg 2", "msg 3"],
"Name": "mkyong"
}