一、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]
python 调用文件夹内模块 python如何调用文件
1.1使用open()函数打开文件夹可以通过内置函数open()来打开一个文件程序中,,并用相关的方法读或写文件文件中的内容以供程序的处理和使用,同时可以将文件看作Python中的一种数据类型。是用函数open()的语法格式如下。open(filename, mode='r', buffering=None, encoding=None, errors=None,
newline=Non