<!-- Just the annotations; use this dependency if you want to attach annotations to classes without connecting them to the code. --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson-2-version}</version> </dependency>
<!-- databinding; ObjectMapper, JsonNode and related classes are here --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson-2-version}</version> </dependency>
<!-- smile (binary JSON). Other artifacts in this group do other formats. --> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-smile</artifactId> <version>${jackson-2-version}</version> </dependency> <!-- JAX-RS provider --> <dependency> <groupId>com.fasterxml.jackson.jaxrs</groupId> <artifactId>jackson-jaxrs-json-provider</artifactId> <version>${jackson-2-version}</version> </dependency> <!-- Support for JAX-B annotations as additional configuration --> <dependency> <groupId>com.fasterxml.jackson.module</groupId> <artifactId>jackson-module-jaxb-annotations</artifactId> <version>${jackson-2-version}</version> </dependency>比如我们需要解析的Json数据如下:{ "id": 123, "name": "Pankaj", "permanent": true, "address": { "street": "Albany Dr", "city": "San Jose", "zipcode": 95129 }, "phoneNumbers": [ 123456, ], "role": "Manager", "cities": [ "Los Angeles", "New York" ], "properties": { "age": "29 years", "salary": "1000 USD" } }对应的Model Class 如下:import java.util.Arrays; import java.util.List; import java.util.Map;
public static void main(String[] args) throws IOException {
//read json file data to String byte[] jsonData = Files.readAllBytes(Paths.get("C:\employee.txt"));
//create ObjectMapper instance ObjectMapper objectMapper = new ObjectMapper();
//convert json string to object Employee emp = objectMapper.readValue(jsonData, Employee.class);
System.out.println("Employee Object
"+emp);
//convert Object to json string Employee emp1 = createEmployee(); //configure Object mapper for pretty print objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
//writing to console, can write to any output stream such as file StringWriter stringEmp = new StringWriter(); objectMapper.writeValue(stringEmp, emp1); System.out.println("Employee JSON is
"+stringEmp); }