使用Java中的Gson进行漂亮打印格式的JSON文件输入输出?

6
  • 我已经知道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;

}

我想创建一个包含以下内容的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"
            },
    ]
  • I managed to create and write a json file of Person objects (as gson json Person objects), and read it, but again only as Person objects, where every line is an independent object, not a part of a List or Array of Person objects, like this
    {"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"}
    

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

  • 我还能够硬编码一个文件,其中包含以下信息和格式,并成功地获取到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"
          },
    ]

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

我修改了我的员工类,使其与他的虚拟对象匹配,我认为这样更好,现在它看起来是这样的。

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

欢迎来到 Stack Overflow!请参观一下,了解本站的运作方式以及哪些问题适合在此提问,并相应地编辑您的问题。另请参阅:为什么“有人能帮我吗?”不是一个实际问题? - Joe C
可能是在Java中漂亮地打印JSON的重复问题。 - Basil Battikhi
2个回答

7

由于你是新手,我会快速地向你介绍如何使用漂亮的格式将一个 ListEmployee 对象写入到 JSON 文件中:

步骤1: 创建一个方法,接受一个 List 和一个 String filePath

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

步骤2: 使用启用了漂亮格式的 Gson 对象进行构建:

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

步骤3: 使用 FileWriter 将你的 List<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"
  }
]

我希望这篇文章能够帮助你的学习过程。

注意:本文中使用了一些随机的员工姓名和细节信息,你可以将其替换为你需要的内容。


小注释:由于代码片段使用了 Java 7 中提供的 try-with-resources,因此在此调用 writer.close() 是多余的(会自动调用)。一般来说(如果不使用 try-with-resources),关闭资源的良好实践是使用 finally 块,以避免在出现异常时可能导致资源泄漏。 - Alon Eirew

1
首先将这些对象存储到一个对象列表中。然后添加以下代码以进行漂亮的打印输出。
Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson (list));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接