json 文件 I/O 在 java 中使用 gson 具有漂亮的打印格式?

json file I/O with pretty print format using gson in java?

:

public class Employee implements Serializable {

    private String lastName;
    private String address;
    private int id;
    private String name;

}

我想创建一个 json 文件,其内容完全如下

 [
            {
                "id":1,
                "name": "John",
                "lastName": "Doe",
                "address": "NY City"
            },
            {
                "id":2,
                "name": "John",
                "lastName": "Doe",
                "address": "Canada"
            },
            {
                "id":3,
                "name": "John",
                "lastName": "Doe",
                "address": "Las Vegas"
            },
    ]

但这不是我希望我的最终程序做的。

 [
          {
              "id":1,
              "name": "John",
              "lastName": "Doe",
              "address": "NY City"
          },
          {
              "id":2,
              "name": "John",
              "lastName": "Doe",
              "address": "Canada"
          },
          {
              "id":3,
              "name": "John",
              "lastName": "Doe",
              "address": "Las Vegas"
          },
    ]

但我不知道如何使用 java 程序创建和写入此 json 文件 作为 Person 对象的数组,其中每个 Person 对象都是此对象的一部分 具有漂亮打印格式的列表或数组,就像我硬编码的那样 我能够阅读。 我怎样才能优雅地做到这一点?

编辑--- 非常感谢@Shyam!

这是我的最终代码,希望对大家有所帮助。

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

public class TestFileOfGsonWriter {

    Gson gson ;
    String filePath ;
    BufferedReader bufferToReader ;


    public TestFileOfGsonWriter()
    {
        this.filePath = 
                "C:\FileOfGsonSingleListOfEmployees\employees.json" ;
    }

    public List<Employee> createEmployees()
    {
        Employee arya = new Employee("Stark", "#81, 2nd main, Winterfell", 2, "Arya");
        Employee jon = new Employee("Snow", "#81, 2nd main, Winterfell", 1, "Jon");
        Employee sansa = new Employee("Stark", "#81, 2nd main, Winterfell", 3, "Sansa");

        List<Employee> employees = new ArrayList<>();
        employees.add(jon);
        employees.add(arya);
        employees.add(sansa);
        return employees ;
    }

    public void jsonWriter(List<Employee> employees, String filePath)
    {
        this.gson = new GsonBuilder().setPrettyPrinting().create();
        try(FileWriter writer = new FileWriter(filePath))
        {
            gson.toJson(employees,writer);
            writer.close();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }

    public void showEmployeeObjects()
    {
        try {
            List<Employee> employees = this.getAllEmployees();
            employees.forEach(e -> Employee.showEmployeeDetails(e));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public ArrayList<Employee> getAllEmployees() throws IOException
    {
        FileReader reader = new FileReader(this.filePath);
        this.bufferToReader = new BufferedReader(reader) ;
        ArrayList <Employee> employees = this.gson.fromJson(getJson(), 
                new TypeToken<ArrayList<Employee>>(){}.getType());
        return employees ;
    }

    private String getJson() throws IOException
    {
        StringBuilder serializedEmployee = new StringBuilder();
        String line ;
        while ( (line = this.bufferToReader.readLine()) != null )
        {
            serializedEmployee.append(line);
        }
        this.bufferToReader.close();
        return serializedEmployee.toString();
    }

    public static void main(String[] args) {
        TestFileOfGsonWriter testWriting = new TestFileOfGsonWriter() ;
        List<Employee> employees = testWriting.createEmployees();
        testWriting.jsonWriter(employees, testWriting.filePath);
        testWriting.showEmployeeObjects();
    }
}

我修改了我的 Employee class 所以它会与他的虚拟对象匹配,我认为这更好,这就是现在的样子。

import java.io.Serializable;

public class Employee implements Serializable {

    private static final long serialVersionUID = 1L;
    String name ;
    String address;
    String lastName ;
    int id ;

    public static void showEmployeeDetails(Employee e)
    {
        System.out.println();
        System.out.println("Employee's name: "+e.name);
        System.out.println("Employee's last name"+e.lastName);
        System.out.println("Employee's address: "+e.address);
        System.out.println("Employee's ID: "+e.id);
    }

    public Employee(String myName, String myAddress, int myId, String myLastName)
    {
        this.name = myName ;
        this.address = myAddress;
        this.lastName = myLastName;
        this.id = myId ;
    }
}

因此,程序创建的 json 文件看起来正是我想要的:

[
  {
    "name": "Snow",
    "address": "#81, 2nd main, Winterfell",
    "lastName": "Jon",
    "id": 1
  },
  {
    "name": "Stark",
    "address": "#81, 2nd main, Winterfell",
    "lastName": "Arya",
    "id": 2
  },
  {
    "name": "Stark",
    "address": "#81, 2nd main, Winterfell",
    "lastName": "Sansa",
    "id": 3
  }
]

最后,这是输出:

Employee's name: Snow
Employee's last nameJon
Employee's address: #81, 2nd main, Winterfell
Employee's ID: 1

Employee's name: Stark
Employee's last nameArya
Employee's address: #81, 2nd main, Winterfell
Employee's ID: 2

Employee's name: Stark
Employee's last nameSansa
Employee's address: #81, 2nd main, Winterfell
Employee's ID: 3

首先将这些对象存储到对象列表中。然后添加这行漂亮的打印代码。

Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson (list));

作为新手,我将快速引导您完成将 ListEmployee 个对象写入 JSON 文件并打印漂亮的过程:

第 1 步: 创建一个接受列表和 String filePath:

的方法

public void jsonWriter(List<Employee> employees, String filePath)

步骤 2: 构建一个 Gson 启用漂亮打印的对象:

Gson gson = new GsonBuilder().setPrettyPrinting().create();

第 3 步: 使用 FileWriterList<Employee> 写入给定 filePath 中的 JSON 文件:

       try(FileWriter writer = new FileWriter(filePath)) {
            gson.toJson(employees, writer);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

最后,整个方法应该如下所示:

public void jsonWriter(List<Employee> employees, String filePath) {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        try(FileWriter writer = new FileWriter(filePath)) {
            gson.toJson(employees, writer);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

第 4 步: 现在,构建您的 Employee 对象,将它们添加到 List 并使用适当的 filePath 调用此方法

        Employee arya = new Employee("Stark", "#81, 2nd main, Winterfell", 2, "Arya");
        Employee jon = new Employee("Snow", "#81, 2nd main, Winterfell", 1, "Jon");
        Employee sansa = new Employee("Stark", "#81, 2nd main, Winterfell", 3, "Sansa");

        List<Employee> employees = new ArrayList<>();
        employees.add(jon);
        employees.add(arya);
        employees.add(sansa);

        jsonWriter(employees, "C:/downloads/employees.json");

在 运行 这段代码之后,JSON 文件的内容将如下所示:

[
  {
    "lastName": "Snow",
    "address": "#81, 2nd main, Winterfell",
    "id": 1,
    "name": "Jon"
  },
  {
    "lastName": "Stark",
    "address": "#81, 2nd main, Winterfell",
    "id": 2,
    "name": "Arya"
  },
  {
    "lastName": "Stark",
    "address": "#81, 2nd main, Winterfell",
    "id": 3,
    "name": "Sansa"
  }
]

希望这对您的学习过程有所帮助。

注意: 我使用了一些随机的 Employee 名称和详细信息。您可以将其替换为您需要的详细信息。