Java 将 对象转 JSON 文件

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

package com.onitroad.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.onitroad.demo.model.Department;
import com.onitroad.demo.model.Employee;
public class JaxbExample 
{
	public static void main(String[] args) 
	{
		Employee employee = new Employee(1, "JackLi", "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();
	    }
	}
}
日期:2020-09-17 00:09:37 来源:oir作者:oir