# JAXB 将对象转换为 JSON 示例

> 原文： [https://howtodoinjava.com/jaxb/convert-object-to-json-moxy/](https://howtodoinjava.com/jaxb/convert-object-to-json-moxy/)

Java 示例**将 Java 对象转换为 JSON 字符串**或将 JSON 写入文件。 本示例将 [MOXy](https://wiki.eclipse.org/EclipseLink/Examples/MOXy) 与 JAXB 一起使用，以**将 Java 对象编组为 JSON**。 MOXy 实现 JAXB，使开发人员可以通过注释提供其映射信息，并提供 JAXB 默认不提供的许多丰富功能。

## 1\. MOXy 依赖

包括 MOXy 到项目运行时。

```java
<dependency>
	<groupId>org.eclipse.persistence</groupId>
	<artifactId>org.eclipse.persistence.moxy</artifactId>
	<version>2.5.2</version>
</dependency>

```

## 2\. Java 对象到 JSON 字符串

#### 2.1 添加 JAXB 注释

```java
@XmlRootElement(name = "employee")
@XmlAccessorType(XmlAccessType.PROPERTY)
public class Employee implements Serializable {

	private static final long serialVersionUID = 1L;

	private Integer id;
	private String firstName;
	private String lastName;
	private Department department;

	public Employee() {
		super();
	}

	//Setters and Getters
}

```

```java
@XmlRootElement(name = "department")
@XmlAccessorType(XmlAccessType.PROPERTY)
public class Department implements Serializable {

	private static final long serialVersionUID = 1L;

	Integer id;
	String name;

	public Department() {
		super();
	}

	//Setters and Getters
}

```

#### 2.2 添加`jaxb.properties`

当您获得`JAXBContext`的实例时，JAXB 将检查`jaxb.properties`文件并构造上下文。 在这里，您从 MOXy 库中注入了`JAXBContextFactory`。

> 将`jaxb.properties`文件放在放置 JAXB 注释类的同一包中。

```java
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

```

#### 2.3 将对象转换为 JSON

现在使用`javax.xml.bind.Marshaller`类将对象转换为 json。

```java
package com.howtodoinjava.demo;

import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import org.eclipse.persistence.jaxb.MarshallerProperties;
import com.howtodoinjava.demo.model.Department;
import com.howtodoinjava.demo.model.Employee;

public class JaxbExample 
{
	public static void main(String[] args) 
	{
		Employee employee = new Employee(1, "Lokesh", "Gupta", new Department(101, "IT"));

		jaxbObjectToJSON(employee);
	}

	private static void jaxbObjectToJSON(Employee employee) 
	{
	    try 
	    {
	        JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);
	        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

	        // To format JSON
	        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); 

	        //Set JSON type
	        jaxbMarshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
	        jaxbMarshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, true);

	        //Print JSON String to Console
	        StringWriter sw = new StringWriter();
	        jaxbMarshaller.marshal(employee, sw);
	        System.out.println(sw.toString());
	    } 
	    catch (JAXBException e) 
	    {
	        e.printStackTrace();
	    }
	}
}

```

程序输出：

```java
{
   "employee" : {
      "department" : {
         "id" : 101,
         "name" : "IT"
      },
      "firstName" : "Lokesh",
      "id" : 1,
      "lastName" : "Gupta"
   }
}

```

> 阅读更多：[将 Java 对象转换为 XML](https://howtodoinjava.com/jaxb/write-object-to-xml/)

## 3\. Java 对象到 JSON 文件

使用上面的代码，现在输出到 json 文件。

```java
package com.howtodoinjava.demo;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import org.eclipse.persistence.jaxb.MarshallerProperties;
import com.howtodoinjava.demo.model.Department;
import com.howtodoinjava.demo.model.Employee;

public class JaxbExample 
{
	public static void main(String[] args) 
	{
		Employee employee = new Employee(1, "Lokesh", "Gupta", new Department(101, "IT"));

		jaxbObjectToJSON(employee);
	}

	private static void jaxbObjectToJSON(Employee employee) 
	{
	    try 
	    {
	        JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);
	        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

	        // To format JSON
	        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); 

	        //Set JSON type
	        jaxbMarshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
	        jaxbMarshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, true);

	         //Store JSON to File
	        File file = new File("employee.json");
	        jaxbMarshaller.marshal(employee, file);
	    } 
	    catch (JAXBException e) 
	    {
	        e.printStackTrace();
	    }
	}
}

```

程序输出：

```java
{
   "employee" : {
      "department" : {
         "id" : 101,
         "name" : "IT"
      },
      "firstName" : "Lokesh",
      "id" : 1,
      "lastName" : "Gupta"
   }
}

```

请在与该**相关的注释部分将我的问题转换为 json 示例**。

学习愉快！