📜  如何在Java应用程序中设置 Jackson?

📅  最后修改于: 2022-05-13 01:55:34.022000             🧑  作者: Mango

如何在Java应用程序中设置 Jackson?

JSON(Javascript Object Notation)是 Web 应用程序世界中最流行的数据交换格式。浏览器可以轻松解析 json 请求并将它们转换为 javascript 对象。服务器解析 json 请求,处理它们,并生成新的 json 响应。 JSON 具有自我描述性且易于理解。将Java对象转换为json的过程称为序列化,将json转换为Java对象的过程称为反序列化。

考虑下面的示例图来了解 json 的文件结构,如下所示:

插图:

我们有一个 Student 类,它有 id、name、address、city、hobby 等属性。下面我们来了解一下对应的json文件是怎样的:

{"id":"S1122","name":"Jane","address":"XYZ Street","city":"Mumbai","hobby":"Badminton, Dancing"}

JSON 数据以名称/值对的形式写入,其中名称是属性/属性名称,值是该属性的值。



现在让我们在继续为任何Java应用程序设置 Jackson 之前讨论一下 Jackson JSON 库。

  • 对于Java应用程序,使用 Json字符串是非常困难的。因此,在Java应用程序中,我们需要一个 json 解析器来解析 Json 文件并将它们转换为Java对象。
  • Jackson 就是这样一种用于解析和生成 Json 文件的Java Json 库。它内置了 Object Mapper 类,用于解析 json 文件并将其反序列化为自定义Java对象。它有助于从Java对象生成 json。
  • Jackson 还有一个 Jackson Json Parser 和 Jackson Json Generator,它一次解析并生成一个 json 标记。

设置:-

要在我们的应用程序中使用 Jackson 库,我们需要在我们的 maven 项目的 pom.xml 文件中添加以下依赖项。


   com.fasterxml.jackson.core
   jackson-core
   2.9.6



   com.fasterxml.jackson.core
   jackson-annotations
   2.9.6



   com.fasterxml.jackson.core
   jackson-databind
   2.9.6

实现:我们来了解一下Jackson库是如何解析json文件并生成的。

让我们考虑具有名称、id、deptName、salary、 rating 等属性的 Employee 类。我们使用 Jackson 库从 Employee 对象生成一个 json 文件。我们更新了它的属性之一——deptName。我们将员工对象序列化为 json 文件,然后将其反序列化回员工对象,并使用更新的 deptName 属性值。

示例 1



Java
//  Java Program to Illustrate Setting Up of Jackson by
//  parsing Jackson library json files and
//  generating the same
 
// Importing required classes
import java.io.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an employee object with it's attributes
        // set
        Employee employee = getEmployee();
        ObjectMapper mapper = new ObjectMapper();
 
        // Try block to check for exceptions
        try {
 
            // Serializes emp object to a file employee.json
            mapper.writeValue(
                new File(
                    "/home/suchitra/Desktop/suchitra/projects/java-concurrency-examples/jackson-parsing/src/main/resources/employee.json"),
                employee);
 
            // Deserializes emp object in json string format
            String empJson
                = mapper.writeValueAsString(employee);
            System.out.println(
                "The employee object in json format:"
                + empJson);
            System.out.println(
                "Updating the dept of emp object");
 
            // Update deptName attribute of emp object
            employee.setDeptName("Devops");
            System.out.println(
                "Deserializing updated emp json ");
 
            // Reading from updated json and deserializes it
            // to emp object
            Employee updatedEmp = mapper.readValue(
                mapper.writeValueAsString(employee),
                Employee.class);
 
            // Print and display the updated employee object
            System.out.println("Updated emp object is "
                               + updatedEmp.toString());
        }
  
        // Catch block to handle exceptions
 
        // Catch block 1
        // Handling JsonGenerationException
        catch (JsonGenerationException e) {
 
            // Display the exception along with line number
            // using printStackTrace() method
            e.printStackTrace();
        }
 
        // Catch block 2
        // Handling JsonmappingException
        catch (JsonMappingException e) {
 
            // Display the exception along with line number
            // using printStackTrace() method
            e.printStackTrace();
        }
 
        // Catch block 3
        // handling generic I/O exceptions
        catch (IOException e) {
 
            // Display the exception along with line number
            // using printStackTrace() method
            e.printStackTrace();
        }
    }
 
    // Method 2
    // To get the employees
    private static Employee getEmployee()
    {
        // Creating an object of Employee class
        Employee emp = new Employee();
        emp.setId("E010890");
        emp.setName("James");
        emp.setDeptName("DBMS");
        emp.setRating(5);
        emp.setSalary(1000000.00);
 
        // Returning the employee
        return emp;
    }
}
 
// Class 2
// Helper class
class Employee {
 
    // Member variables of this class
    private String id;
    private String name;
    private String deptName;
    private double salary;
    private int rating;
 
    // Member methods of this class
    public String getId() { return id; }
    public void setId(String id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public String getDeptName() { return deptName; }
    public void setDeptName(String deptName)
    {
        // This keyword refers to current instance
        this.deptName = deptName;
    }
 
    public double getSalary() { return salary; }
    public void setSalary(double salary)
    {
        this.salary = salary;
    }
    public int getRating() { return rating; }
    public void setRating(int rating)
    {
        this.rating = rating;
    }
 
    @Override public String toString()
    {
        return "Employee [id=" + id + ", name=" + name
            + ", deptName=" + deptName + ", salary="
            + salary + ", rating=" + rating + "]";
    }
}


Java
//  Java Program to Illustrate Setting Up of Jackson by
//  Reading an object from an InputStream
// Using Object Mapper & deserializing to object
 
// Importing required classes
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
 
// Class 1
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an object mapper instance
        ObjectMapper mapper = new ObjectMapper();
 
        // Try block to check for exceptions
        try {
 
            // input stream points to a json file in
            // src/main/resources folder
            InputStream inputStream = new FileInputStream(
                "/home/suchitra/Desktop/suchitra/projects/java-concurrency-examples/jackson-parsing/src/main/resources/employee.json");
 
            // Deserializes from json file to employee
            // object
            Employee emp = mapper.readValue(inputStream,
                                            Employee.class);
            System.out.println(emp.toString());
        }
 
        // Catch blocks to handle the exceptions
 
        // Catch block 1
        // Handling FileNotFoundException
        catch (FileNotFoundException e) {
 
            // Displaying the exception along with line
            // number using printStackTrace()
            e.printStackTrace();
        }
 
        // Catch block 2
        catch (JsonParseException e) {
 
            // Displaying the exception along with line
            // number using printStackTrace()
            e.printStackTrace();
        }
 
        // Catch block 3
        catch (JsonMappingException e) {
            e.printStackTrace();
        }
 
        // Catch block 4
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}
}
 
// Class 2
// Helper class
class Employee {
 
    // Member variables of this class
    private String id;
    private String name;
    private String deptName;
    private double salary;
    private int rating;
 
    // Member methods of this class
    public String getId() { return id; }
    public void setId(String id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public String getDeptName() { return deptName; }
    public void setDeptName(String deptName)
    {
        // This keyword refers to current object itself
        this.deptName = deptName;
    }
 
    public double getSalary() { return salary; }
 
    public void setSalary(double salary)
    {
        this.salary = salary;
    }
 
    public int getRating() { return rating; }
 
    public void setRating(int rating)
    {
        this.rating = rating;
    }
 
    @Override public String toString()
    {
        return "Employee [id=" + id + ", name=" + name
            + ", deptName=" + deptName + ", salary="
            + salary + ", rating=" + rating + "]";
    }
}


输出:

The employee object in json format:{"id":"E010890","name":"James","deptName":"DBMS","salary":1000000.0,"rating":5}
Updating the dept of emp object
Deserializing updated emp json 
Updated emp object is Employee [id=E010890, name=James, deptName=Devops, salary=1000000.0, rating=5]

现在让我们进入下一个示例,我们将使用 Jackson 从使用 Object Mapper 的 InputStream 读取对象并将其反序列化为Java对象。

我们将使用 ObjectMapper 类的readValue() 方法来读取文件。

{"id":"E010890","name":"James","deptName":"DBMS","salary":1000000.0,"rating":5}

例子

Java

{"id":"E010890","name":"James","deptName":"DBMS","salary":1000000.0,"rating":5}

输出:

ObjectMapper mapper = new ObjectMapper();
InputStream inputStream = new FileInputStream("file-path"); 
Employee emp = mapper.readValue(inputStream, Employee.class);