java json字符串转对象_json转换为java对象_ json字符串转对象数组使用JAXB

位置:首页>文章>详情   分类: 教程分享 > Java教程   阅读(1232)   2023-03-28 11:29:14
      将JSON转换为Java Object的Java示例。您可以将JSON String解组为Object或将JSON文件解组为Object。此示例使用MOXy和JAXB将JSON解组为Java对象。MOXy实现了JAXB,允许开发人员通过注释提供他们的映射信息,并提供许多JAXB默认不提供的丰富功能。
 

1)MOXy依赖

将MOXy包含在项目运行时中。
 
pom.xml
<dependency>
    <groupId>org.eclipse.persistence</groupId>
    <artifactId>org.eclipse.persistence.moxy</artifactId>
    <version>2.5.2</version>
</dependency>

2)JSON文件到Java对象

2.1)添加JAXB注释

Employee.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
}
 
Department.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文件并构造上下文。在这里,您JAXBContextFactory从MOXy库中注入。
jaxb.properties文件放在放置JAXB注释类的同一个包中。
jaxb.properties
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

2.3)将JSON转换为Object

现在使用javax.xml.bind.UnMarshallerclass将json转换为object。
JaxbExample.java
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.eclipse.persistence.jaxb.MarshallerProperties;
import org.eclipse.persistence.jaxb.UnmarshallerProperties;
import com.howtodoinjava.demo.model.Department;
import com.howtodoinjava.demo.model.Employee;
 
public class JaxbExample
{
    public static void main(String[] args)
    {  
        String fileName = "employee.json";
        jaxbJsonToObject(fileName);
    }
     
    private static void jaxbJsonToObject(String fileName) {
        File xmlFile = new File(fileName);
         
        JAXBContext jaxbContext;
        try
        {
            jaxbContext = JAXBContext.newInstance(Employee.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
             
            //Set JSON type
            jaxbUnmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json");
            jaxbUnmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, true);
             
            Employee employee = (Employee) jaxbUnmarshaller.unmarshal(xmlFile);
             
            System.out.println(employee);
        }
        catch (JAXBException e)
        {
            e.printStackTrace();
        }
    }
}
 
输出结果:
Employee [id=1, firstName=Lokesh, lastName=Gupta, department=Department [id=101, name=IT]]
要读取的JSON文件是:
employee.json
{
   "employee" : {
      "department" : {
         "id" : 101,
         "name" : "IT"
      },
      "firstName" : "Lokesh",
      "id" : 1,
      "lastName" : "Gupta"
   }
}
 

3)将JSON字符串转换为Java对象

您可以以STring形式获取JSON,然后直接填充到Java对象。
JaxbExample.java
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.eclipse.persistence.jaxb.MarshallerProperties;
import org.eclipse.persistence.jaxb.UnmarshallerProperties;
import com.howtodoinjava.demo.model.Department;
import com.howtodoinjava.demo.model.Employee;
 
public class JaxbExample
{
    public static void main(String[] args)
    {  
        String jsonString = "{\"employee\":{\"department\":{\"id\":101,\"name\":\"IT\"},
                            \"firstName\":\"Lokesh\",\"id\":1,\"lastName\":\"Gupta\"}}";
        jaxbJsonStringToObject(jsonString);
    }
     
    private static void jaxbJsonStringToObject(String jsonString)
    {
        JAXBContext jaxbContext;
        try
        {
            jaxbContext = JAXBContext.newInstance(Employee.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
             
            //Set JSON type
            jaxbUnmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json");
            jaxbUnmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, true);
             
            Employee employee = (Employee) jaxbUnmarshaller.unmarshal(new StringReader(jsonString));
             
            System.out.println(employee);
        }
        catch (JAXBException e)
        {
            e.printStackTrace();
        }
    }
}

输出:
Employee [id=1, firstName=Lokesh, lastName=Gupta, department=Department [id=101, name=IT]]

4)Java对象到JSON

将Java对象转换为JSON的示例。
JAXBExample.java
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();
        }
    }
}

输出:
{
   "employee" : {
      "department" : {
         "id" : 101,
         "name" : "IT"
      },
      "firstName" : "Lokesh",
      "id" : 1,
      "lastName" : "Gupta"
   }
}
标签: java json
地址:https://www.leftso.com/article/476.html

相关阅读

java json字符串转对象_json转换为java对象_ json字符串转对象数组
Java EE 8 JSON Pointer讲解,Java EE 8包含JSON处理API的更新,并为最新的JSON标准提供最新的IEFT标准。
使用Jackson写巨大的JSON文件
handlerexceptionresolver 返回json
前言值得一提的是JSON只有数组数据类型
说明:json除了键值对的形式以外,还包括Array数列形式,这在mysql5.7及以上也是支持的,对Array中元素的操作相当于直接对键值对中的值操作,少了“键”的定位这一步,这里不单独展示,...
前言学习使用Google GSON库将Java对象序列化为JSON表示形式,并将JSON字符串反序列化为等效的Java对象
fastJSON字符串类型数据中的日期转换为Java bean的日期对象
备受期待的Java Enterprise Edition 8发布了两个令人兴奋的新API(JSON-Binding 1.0和Java EE Security 1.0)并改进了当前的API(JAX...
httpclient4.5使用详解 httpclient 4.5 post传递json参数