多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# Jackson2 – 将 Java 对象转换为 JSON,并将 JSON 字符串转换为对象 > 原文: [https://howtodoinjava.com/jackson/jackson-2-convert-json-to-from-java-object/](https://howtodoinjava.com/jackson/jackson-2-convert-json-to-from-java-object/) 在本教程中,我们将学习使用 [**Jackson2**](https://github.com/FasterXML/jackson) 库将 **JSON 转换为 Java 对象** – 和**将 Java 对象转换为 JSON**。 ```java Table of Contents Jackson2 maven dependency Convert Java object to JSON Convert JSON to Java object ``` ## 1.Jackson2 Maven 依赖 要将 Jackson2 库包含在您的项目中,请在`pom.xml`中包含以下依赖项。 ```java <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.6.4</version> </dependency> ``` 您可以从 [**maven 站点**](https://mvnrepository.com/artifact/com.fasterxml.jackson.core)找到可下载的 jar 文件。 ## 2.将 Java 对象转换为 JSON 的示例 在简单的 pojo 对象之间进行转换时,Jackson 非常直接。 通常只涉及两个步骤, * 创建`com.fasterxml.jackson.databind.ObjectMapper`的实例 * 使用`objectMapper.writeValueAsString()`方法将 pojo 转换为 JSON ```java //Simple POJO Employee emp = new Employee(1, "Lokesh Gupta", 34, "India"); //Object mapper instance ObjectMapper mapper = new ObjectMapper(); //Convert POJO to JSON String json = mapper.writeValueAsString(emp); ``` #### 2.1 将 Java 对象转换为 JSON 的 Java 程序 ```java package com.howtodoinjava.jackson2.example; import java.io.IOException; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.howtodoinjava.jackson2.example.pojo.Employee; public class FromJavaPojoToJSON { public static void main(String[] args) { Employee emp = new Employee(1, "Lokesh Gupta", 34, "India"); ObjectMapper mapper = new ObjectMapper(); try { String json = mapper.writeValueAsString(emp); System.out.println(json); //Use pretty print for printing the output String beutifulJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp); System.out.println(beutifulJson); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ``` ```java Output: {"id":1,"name":"Lokesh Gupta","age":34,"location":"India"} { "id" : 1, "name" : "Lokesh Gupta", "age" : 34, "location" : "India" } ``` 这里使用的 POJO 对象是: ```java package com.howtodoinjava.jackson2.example.pojo; public class Employee { private Integer id; private String name; private Integer age; private String location; public Employee(Integer id, String name, Integer age, String location) { super(); this.id = id; this.name = name; this.age = age; this.location = location; } //Setters and Getters will be added here @Override public String toString() { return "Employee [id=" + id + ", name=" + name + ", age=" + age + ", location=" + location + "]"; } } ``` ## 3.将 JSON 转换为 Java 对象的示例 就像上面的示例一样,从 JSON 到 POJO 的转换也仅涉及两个步骤, * 创建`com.fasterxml.jackson.databind.ObjectMapper`的实例 * 使用`objectMapper.readValue()`方法将 JSON 转换为 POJO 例如: ```java //JSON input String json = "{\"id\":1,\"name\":\"Lokesh Gupta\",\"age\":34,\"location\":\"India\"}"; //Object mapper instance ObjectMapper mapper = new ObjectMapper(); //Convert JSON to POJO Employee emp = mapper.readValue(json, Employee.class); ``` 我们可以在 Java 中读取 json 文件,并将其传递给 jackson 库。 #### 3.1 将 JSON 转换为 Java 对象的 Java 程序 ```java package com.howtodoinjava.jackson2.example; import java.io.IOException; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.howtodoinjava.jackson2.example.pojo.Employee; public class FromJSONToPOJO { public static void main(String[] args) { String json = "{\"id\":1,\"name\":\"Lokesh Gupta\",\"age\":34,\"location\":\"India\"}"; ObjectMapper mapper = new ObjectMapper(); try { Employee emp = mapper.readValue(json, Employee.class); System.out.println(emp); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ``` 程序输出。 ```java Employee [id=1, name=Lokesh Gupta, age=34, location=India] ``` 请不要忘记在 POJO 类中添加默认的构造器,否则会出现此错误: ```java com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class com.howtodoinjava.jackson2.example.pojo.Employee]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?) at [Source: {"id":1,"name":"Lokesh Gupta","age":34,"location":"India"}; line: 1, column: 2] at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148) at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1106) at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:296) at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:133) at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3736) at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2726) at com.howtodoinjava.jackson2.example.FromJSONToPOJO.main(FromJSONToPOJO.java:18) ``` 以上就是使用 Jackson2 库将 Java 对象转换为 JSON 并将 JSON 字符串转换为 Java 对象的所有示例。 让我知道您是否对如何将 json 对象转换为 java 对象有任何疑问。 学习愉快!