java读取json文件(Gson)

一、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]

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值