java读取json文件(Gson)
json
适用于现代 C++ 的 JSON。
项目地址:https://gitcode.com/gh_mirrors/js/json
免费下载资源
·
一、Gson的基本用法
Gson提供了fromJson() 和toJson() 两个直接用于解析和生成的方法,前者实现反序列化,后者实现了序列化;同时每个方法都提供了重载方法;Gson提供了良好的容错率,即使你的json文件没有写对,例如少写引号或者多写引号,都可以解析出来。
二、举例
读取下列文件中的内容
package com.fjh.json;
public class Person {
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
package com.fjh.json;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Data {
private int rows;
private List<Person> datas = new ArrayList<Person>();
String time;
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
public List<Person> getDatas() {
return datas;
}
public void setDatas(List<Person> datas) {
this.datas = datas;
}
public String getFileContent(String fileName) {
String userPath = System.getProperty("user.dir");
StringBuffer content = new StringBuffer();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(new File(userPath + "/" + fileName)));
String line = null;
while ((line = reader.readLine()) != null) {
content.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return content.toString();
}
@Override
public String toString() {
return "Data [rows=" + rows + ", datas=" + datas + ", time=" + time + "]";
}
}
package com.fjh.json;
import com.google.gson.Gson;
public class GsonTest {
public static void main(String[] args) {
Data data = new Data();
String content = data.getFileContent("Persons.json");
Gson gson = new Gson();
Data fromJson = gson.fromJson(content, Data.class);
System.out.println(fromJson);
}
}
读取结果
Data [rows=3, datas=[Person [id=1, name=张三, age=20], Person [id=2, name=zz, age=21], Person [id=3, name=lw, age=22]], time=2019-07-01]
GitHub 加速计划 / js / json
18
5
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:3 个月前 )
2d42229f
* Support BSON uint64 de/serialization
Signed-off-by: Michael Valladolid <mikevalladolid@gmail.com>
* Treat 0x11 as uint64 and not timestamp specific
Signed-off-by: Michael Valladolid <mikevalladolid@gmail.com>
---------
Signed-off-by: Michael Valladolid <mikevalladolid@gmail.com> 5 天前
1809b3d8
Signed-off-by: Niels Lohmann <mail@nlohmann.me> 5 天前
更多推荐
已为社区贡献2条内容
所有评论(0)