Java Reference
In-Depth Information
Discussion
Jackson provides many ways of working. For simple cases, you can have POJO (plain old
Java objects) converted to/from JSON more-or-less automatically, as is illustrated in
Example 19-1 .
Example 19-1. Reading and Writing POJOs with Jackson
public
public class
class ReadWriteJackson
ReadWriteJackson {
public
public static
static void
void main ( String [] args ) throws
throws IOException {
ObjectMapper mapper = new
new ObjectMapper ();
String jsonInput =
"{\"id\":0,\"firstName\":\"Robin\",\"lastName\":\"Wilson\"}" ;
Person q = mapper . readValue ( jsonInput , Person . class );
System . out . println ( "Read and parsed Person from JSON: " + q );
Person p = new
new Person ( "Roger" , "Rabbit" );
System . out . print ( "Person object " + p + " as JSON = " );
mapper . writeValue ( System . out , p );
}
}
Create a Jackson ObjectMapper which can map POJOs to/from JSON.
M ap the string jsonInput into a Person object with one call to readValue() .
Co nvert the Person object p into JSON with one call to writeValue() .
Running this example produces the following output:
Read and parsed Person from JSON: Robin Wilson
Person object Roger Rabbit as JSON = {"id":0,"firstName":"Roger",
"lastName":"Rabbit","name":"Roger Rabbit"}
As another example, this code reads the “parser description” example file that opened
this chapter; notice the declaration List<String> for the array of contributors:
public
public class
class SoftwareParseJackson
SoftwareParseJackson {
final
final static
static String FILE_NAME = "/json/softwareinfo.json" ;
 
 
 
 
Search WWH ::




Custom Search