一:测试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()); } } }五:运行结果如下: