java读取json文件(Gson)

一、Gson的基本用法

Gson提供了fromJson() 和toJson() 两个直接用于解析和生成的方法,前者实现反序列化,后者实现了序列化;同时每个方法都提供了重载方法;Gson提供了良好的容错率,即使你的json文件没有写对,例如少写引号或者多写引号,都可以解析出来。
二、举例
读取下列文件中的内容
java读取json文件(Gson)_第1张图片

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]

你可能感兴趣的:(java,java实训)