一:测试json数据如下:

{
    'cat':'it',
    'language':[
        {'id':1,'ide':'eclipse','name':'Java'},
        {'id':2,'ide':'XCode','name':'Swift'},
        {'id':3,'ide':'Visual Stdio','name':'C#'}     
    ],
    'pop':true
}

二:新建Student类,

public class Student {
	String name;
	int id;
	String ide;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getIde() {
		return ide;
	}
	public void setIde(String ide) {
		this.ide = ide;
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", id=" + id + ", ide=" + ide + "]";
	}
}

三:接下来用fastjson进行解析,

public class TestJson {

	public static void main(String[] args) {
		String jsonStr = "{'cat':'it','language':[{'id':1,'ide':'eclipse','name':'Java'},{'id':2,'ide':'XCode','name':'Swift'},{'id':3,'ide':'Visual Stdio','name':'C#'}],'pop':true}";
		JSONObject jsonObject = JSONObject.parseObject(jsonStr);
		JSONArray jsonArray = jsonObject.getJSONArray("language");
		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject object = jsonArray.getJSONObject(i);
			String name = object.getString("name");
			String ide = object.getString("ide");
			int id = object.getIntValue("id");
			Student stu = new Student();
			stu.setId(id);
			stu.setIde(ide);
			stu.setName(name);
			System.out.println(stu.toString());
		}
	}
}

 四:fastjson还有更方便的方法,进行解析,

public class TestJson {

	public static void main(String[] args) {
		String jsonStr = "{'cat':'it','language':[{'id':1,'ide':'eclipse','name':'Java'},{'id':2,'ide':'XCode','name':'Swift'},{'id':3,'ide':'Visual Stdio','name':'C#'}],'pop':true}";
		JSONObject jsonObject = JSONObject.parseObject(jsonStr);
		JSONArray jsonArray = jsonObject.getJSONArray("language");
		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject object = jsonArray.getJSONObject(i);
			Student stu = JSON.toJavaObject(object, Student.class);
			System.out.println(stu.toString());
		}
	}
}

五:运行结果如下:

 

 

GitHub 加速计划 / fastj / fastjson
25.69 K
6.51 K
下载
FASTJSON 2.0.x has been released, faster and more secure, recommend you upgrade.
最近提交(Master分支:3 个月前 )
c942c834 - 1 年前
5bc4709b - 1 年前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐