簡體   English   中英

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

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

  • 我已經知道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"
            },
    ]
  • 我設法創建並編寫了一個Person對象的json文件(作為gson json Person對象),然后讀取它,但又只作為Person對象,其中每一行都是一個獨立的對象,而不是List或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"} 

但這不是我想要的最終計划。

  • 我還能夠使用以下信息和格式對文件進行硬編碼,並成功獲取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();
    }
}

我修改了我的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 ;
    }
}

因此,程序創建的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

在您是新手的時候,我將快速引導您完成將Employee對象List編寫為具有漂亮打印的JSON文件的過程:

步驟1:創建一個接受List和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姓名和詳細信息。 您可以將其替換為所需的詳細信息。

首先將這些對象存儲到對象列表中。 然后添加這行代碼以進行漂亮的打印。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM