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

Moe*_*eMe 3 java io json writefile gson

  • 我已经知道 gson 是如何工作的,也知道如何启用漂亮的打印。
  • 我想使用 gson 而不是 simplejson。
  • 我遇到的问题是我无法创建由Employee对象列表组成的文件。
  • 我已经在 stackoverflow、mkyong、google 的 github 和许多其他站点中看到了所有其他java线程,但我仍然无法完成这个简单的事情。
  • 我已经知道如何读取具有这种特定格式的文件,但我无法编写它。
  • 问题是我无法将所有这些东西组合在一个程序中。
  • 启用漂亮打印的 gson 中的对象列表必须具有正确的缩进,并且每个对象必须用逗号分隔,并且这些对象必须包含在[ ]之间。
  • 用代码解释的问题

public class Employee implements Serializable {

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

}
Run Code Online (Sandbox Code Playgroud)

我想创建一个包含以下内容的 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"
            },
    ]
Run Code Online (Sandbox Code Playgroud)
  • 我设法创建并编写了 Person 对象的 json 文件(作为 gson json Person 对象),并读取它,但再次仅作为 Person 对象,其中每一行都是一个独立的对象,而不是列表或 Person 对象数组的一部分, 像这样
    {"id":1,"name": "John","last": "Doe","address": "NY City"}
    {"id":2,"name": "John","last": "Doe","address": "Canada"}
    {"id":3,"name": "John","last": "Doe","address": "Las Vegas"}
    
    Run Code Online (Sandbox Code Playgroud)

但这不是我想要我的最终程序做的事情。

  • 我还能够使用以下信息和格式对文件进行硬编码并成功获取 Person 对象
 [
          {
              "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"
          },
    ]
Run Code Online (Sandbox Code Playgroud)

但我不知道如何使用 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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 ;
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,程序创建的 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
  }
]
Run Code Online (Sandbox Code Playgroud)

最后,这是输出:

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
Run Code Online (Sandbox Code Playgroud)

小智 6

如你是新的,我将快速引导您完成编写过程ListEmployee对象与漂亮打印的JSON文件:

第 1 步:创建一个接受 List 和 a 的方法String filePath

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

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

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

第3步:写下您List<Employee>对给出的一个JSON文件filePath使用FileWriter

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

最后,整个方法应该是这样的:

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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

第 4 步:现在,构建您的Employee对象,将它们添加到 aList并使用适当的调用此方法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");
Run Code Online (Sandbox Code Playgroud)

运行此代码后,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"
  }
]
Run Code Online (Sandbox Code Playgroud)

我希望这会对你的学习过程有所帮助。

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