Jackson 2 之 将Java对象转换为JSON,并将JSON字符串转换为对象

在本教程中,我们将学习使用Jackson 2将JSON转换为Java对象 – 并将Java对象转换为JSON

目录

Jackson 2 Maven依赖项
将Java对象
转换为JSON 将JSON转换为Java对象

1. Jackson 2专家的依赖

要将Jackson 2库包含在您的项目中,请在pom.xml中包含以下依赖项。

<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-core</artifactId>
	<version>2.6.4</version>
</dependency>

您可以从maven网站找到可下载的jar文件。

2.将Java对象转换为JSON示例

在简单的pojo对象之间进行转换时,Jackson非常直接。通常只涉及两个步骤,

  • 创建实例 com.fasterxml.jackson.databind.ObjectMapper
  • 使用objectMapper.writeValueAsString()方法将Pojo转换为JSON
//Simple POJO
Employee emp = new Employee(1, "Saigon", 34, "India");

//Object mapper instance
ObjectMapper mapper = new ObjectMapper();

//Convert POJO to JSON
String json = mapper.writeValueAsString(emp);

2.1。Java程序将Java对象转换为JSON

package com.how2codex.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.how2codex.jackson2.example.pojo.Employee;

public class FromJavaPojoToJSON 
{
	public static void main(String[] args) 
	{
		Employee emp = new Employee(1, "Saigon", 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();
		}
	}
}
输出:

{“ id”:1,“名称”:“ Saigon”,“年龄”:34,“位置”:“印度”}

{
  “ id”:1
  “ name”:“ Saigon”,
  “年龄”:34岁,
  “位置”:“印度”
}

这里使用的POJO对象是:

package com.how2codex.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

例如

//JSON input
String json = "{\"id\":1,\"name\":\"Saigon\",\"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。Java程序将JSON转换为Java对象

package com.how2codex.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.how2codex.jackson2.example.pojo.Employee;

public class FromJSONToPOJO {
	
	public static void main(String[] args) {
		String json = "{\"id\":1,\"name\":\"Saigon\",\"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();
		}
	}

}

程序输出。

Employee [id=1, name=Saigon, age=34, location=India]
请不要忘记在POJO类中添加默认的构造函数,否则会出现以下错误:

com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class com.how2codex.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":"Saigon","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.how2codex.jackson2.example.FromJSONToPOJO.main(FromJSONToPOJO.java:18)

这就是使用Jackson 2库将Java对象转换为JSON并将JSON字符串转换为Java对象的所有示例。

让我知道您是否对如何将json对象转换为java对象有任何疑问。

学习愉快!

saigon has written 1440 articles

Leave a Reply