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