- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
:
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","last": "Doe","address": "NY City"}
{"id":2,"name": "John","last": "Doe","address": "Canada"}
{"id":3,"name": "John","last": "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 对象都是此对象的一部分 具有 pretty-print 格式的列表或数组,就像我硬编码的那样 我能够阅读。我怎样才能以优雅的方式做到这一点?
编辑---非常感谢@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
最佳答案
作为新手,我将快速引导您完成编写 List
的过程。的 Employee
对象到具有 pretty-print 的 JSON 文件:
第 1 步:创建一个接受列表和 String filePath
的方法:
public void jsonWriter(List<Employee> employees, String filePath)
第 2 步:构建 Gson
启用 pretty-print 的对象:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
第 3 步:写下您的 List<Employee>
到给定 filePath
中的 JSON 文件使用 FileWriter
:
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
名称和详细信息。您可以将其替换为所需的详细信息。
关于java - 在 java 中使用 gson 以 pretty-print 格式创建 json 文件 I/O?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46210867/
我已经和 Lua 搞了几天,我想出了一些让我三思而后行的事情。 Lua 5.3 的引用手册我还没有看,因为它似乎很复杂,我会尽快查看。 好的,在 lua 5.3 中,我们知道 print() 返回 n
计算时IO (IO ()) , 两个 (IO ())和 ()是计算出来的,所以为什么 main :: IO (IO ()) main = print (print "Hello, World!")
我不太理解从以下位置收到的输出: print(print(print('aaa'))) aaa None None 先aaa清楚了。但我认为第二个 print(aaa) 会抛出一个错误,因为变量 aa
当我运行下面的 Perl one-liner 时,它会打印 1在每一行的前面,我不想要它。它应该做的只是注释匹配 root 的行. $ cat /etc/passwd | perl -ne 'prin
我发现由于 Xcode 将不再消化 println() 我是 留下 Swift.print() 或 print() 。我的问题是, 两者有什么区别?我没能 在网上或在 swift 前卫郎。 (Swif
我正在开发一个内部 Google Chrome 扩展,它需要一种方法来启动将当前页面打印到打印机。我不希望出现默认的打印对话框(因此,javascript:window.print() 是不可能的)。
我正在将 Perl6 Terminal::Print 模块用于基于控制台的应用程序。 它运行良好 - 但是,现在我需要提示用户输入一串文本。 有什么好的方法可以做到这一点? 最佳答案 这是使用 Ter
在学习第三方的Lua代码时,我发现在主脚本文件的顶部 local insert = table.insert local match = string.match local gsub = strin
在学习第三方的Lua代码时,我发现在主脚本文件的顶部 local insert = table.insert local match = string.match local gsub = strin
我目前正在学习 Python,并开始了一个项目,为 2000-2005 年 MLB 摊牌纸牌游戏创建棒球模拟游戏。这些程序包含棒球比赛的事件,作为单独代码段中间的打印语句(“Jeff 击中单打”,“B
我的问题:在没有多余括号的情况下漂亮地打印表达式的最干净的方法是什么? 我有以下 lambda 表达式的表示: Term ::= Fun(String x, Term t) | App(
为了在 Julia 中创建可打印的新类型,应该定义哪些方法?我认为应该只定义 show,然后它将引发其他函数的行为,例如: 打印 字符串 repl_show 显示紧凑 展示 需要为新类型定义以下哪些方
我有一个页面,用户可以在其中打印一些带有图像和数据的 pdf。我希望他们能够打印他们想要的文件数量,并且能够暂停它们——这意味着他们可以停止打印并防止打印尚未发送到打印机的文件;当然,已经发送到打印机
CLHS 说 An attempt to print a circular structure with *print-circle* set to nil may lead to looping
正如标题所示,在 Pycharm 中使用自动完成功能时,显示的唯一自动完成选项是:print(args,kwargs) 内置 我希望自动完成功能以“print”完成,因为这是我通常使用的。我正在使用
是否有可能使用 fmt.Println("...") 打印一个 shell 居中对齐的字符串? 最佳答案 作为对这个长期回答问题的更新,可以通过使用 fmt 包中的 * 符号来改进@miltonb 发
我想在控制台屏幕上显示使用 DO 循环完成的计算进度。我可以像这样将进度变量打印到终端: PROGRAM TextOverWrite_WithLoop IMPLICIT NONE INTEGER ::
我正在尝试为我的新对象定义打印方法,并使用传递给 print 的对象名称。使用 deparse(substitute(y)) .这可以完美地使用 print功能明确: obj function (x
我需要安装 dompdf 方面的帮助。我应该将解压的 zip 文件放在目录中的哪个位置?我按照 INSTALL.txt 进行操作,它显示“将下载的包的内容提取到支持的路径之一”。这是否意味着放入“Mo
我的应用程序中有一个 webkit 小部件,您可以打印它。打印效果很好,除了打印时没有图像,即使屏幕上有图像。 打印代码如下: void MainWindow::printPage() { Q
我是一名优秀的程序员,十分优秀!