1.什么是JSON? (http://www.json.org/)
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.
(图片来自:http://www.cnblogs.com/xiaoluo501395377/p/3446605.html)
2.Json数据类型
2-1.json对象
2-2.json数组
ps:JSONObject与JSONArray的区别
3.解析JSON数据(小编使用的GSON进行json数据的解析)
3-1 【JSONObject的解析】
下面是一个json文件:
我们进行解析(解析一部分):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | package cn.edu.bzu.json; import java.io.FileNotFoundException; import java.io.FileReader; import com.google.gson.JsonArray; import com.google.gson.JsonIOException; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; public class Read { public static void main(String args[]){ JsonParser parse = new JsonParser(); //创建json解析器 try { JsonObject json=(JsonObject) parse.parse( new FileReader( "weather.json" )); //创建jsonObject对象 System.out.println( "resultcode:" +json.get( "resultcode" ).getAsInt()); //将json数据转为为int型的数据 System.out.println( "reason:" +json.get( "reason" ).getAsString()); //将json数据转为为String型的数据 JsonObject result=json.get( "result" ).getAsJsonObject(); JsonObject today=result.get( "today" ).getAsJsonObject(); System.out.println( "temperature:" +today.get( "temperature" ).getAsString()); System.out.println( "weather:" +today.get( "weather" ).getAsString()); } catch (JsonIOException e) { e.printStackTrace(); } catch (JsonSyntaxException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } } } |
输出结果:
3-2 【JSONArray的解析】
下面是一个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 }
我们进行解析:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | package cn.edu.bzu.json; import java.io.FileNotFoundException; import java.io.FileReader; import com.google.gson.JsonArray; import com.google.gson.JsonIOException; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; public class ReadJSON { public static void main(String args[]){ try { /*InputStream inStream = request.getInputStream(); ByteArrayOutputStream outSteam = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = inStream.read(buffer)) != -1) { outSteam.write(buffer, 0, len); } String resultStr = new String(outSteam.toByteArray(), "utf-8"); inStream.close(); outSteam.close(); */ JsonParser parser= new JsonParser(); //创建JSON解析器 JsonObject object=(JsonObject) parser.parse( new FileReader( "test.json" )); //创建JsonObject对象 System.out.println( "cat=" +object.get( "cat" ).getAsString()); //将json数据转为为String型的数据 System.out.println( "pop=" +object.get( "pop" ).getAsBoolean()); //将json数据转为为boolean型的数据 JsonArray array=object.get( "language" ).getAsJsonArray(); //得到为json的数组 for ( int i= 0 ;i<array.size();i++){ System.out.println( "---------------" ); JsonObject subObject=array.get(i).getAsJsonObject(); System.out.println( "id=" +subObject.get( "id" ).getAsInt()); System.out.println( "name=" +subObject.get( "name" ).getAsString()); System.out.println( "ide=" +subObject.get( "ide" ).getAsString()); } } catch (JsonIOException e) { e.printStackTrace(); } catch (JsonSyntaxException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } } } |
输出结果:
3-3 【分析】
我们通过Gson进行解析,所以在使用前需要导入Gson.jar
解析json数据时,
1.需要进行创建Gson解析器
2.创建JSONObject对象
3.将json数据转为为相应的数据
fastJson对于json格式字符串的解析主要用到了一下三个类:
JSON:fastJson的解析器,用于JSON格式字符串与JSON对象及javaBean之间的转换。
JSONObject:fastJson提供的json对象。
JSONArray:fastJson提供json数组对象。
我们可以把JSONObject当成一个Map<String,Object>来看,只是JSONObject提供了更为丰富便捷的方法,方便我们对于对象属性的操作。我们看一下源码。
同样我们可以把JSONArray当做一个List<Object>,可以把JSONArray看成JSONObject对象的一个集合。
此外,由于JSONObject和JSONArray继承了JSON,所以说也可以直接使用两者对JSON格式字符串与JSON对象及javaBean之间做转换,不过为了避免混淆我们还是使用JSON。
首先定义三个json格式的字符串,作为我们的数据源。
//json字符串-简单对象型 private static final String JSON_OBJ_STR = "{\"studentName\":\"lily\",\"studentAge\":12}"; //json字符串-数组类型 private static final String JSON_ARRAY_STR = "[{\"studentName\":\"lily\",\"studentAge\":12},{\"studentName\":\"lucy\",\"studentAge\":15}]"; //复杂格式json字符串 private static final String COMPLEX_JSON_STR = "{\"teacherName\":\"crystall\",\"teacherAge\":27,\"course\":{\"courseName\":\"english\",\"code\":1270},\"students\":[{\"studentName\":\"lily\",\"studentAge\":12},{\"studentName\":\"lucy\",\"studentAge\":15}]}";
示例1:JSON格式字符串与JSON对象之间的转换。
示例1.1-json字符串-简单对象型与JSONObject之间的转换
/** * json字符串-简单对象型与JSONObject之间的转换 */ public static void testJSONStrToJSONObject(){ JSONObject jsonObject = JSON.parseObject(JSON_OBJ_STR); //JSONObject jsonObject1 = JSONObject.parseObject(JSON_OBJ_STR); //因为JSONObject继承了JSON,所以这样也是可以的 System.out.println(jsonObject.getString("studentName")+":"+jsonObject.getInteger("studentAge")); }
示例1.2-json字符串-数组类型与JSONArray之间的转换
/** * json字符串-数组类型与JSONArray之间的转换 */ public static void testJSONStrToJSONArray(){ JSONArray jsonArray = JSON.parseArray(JSON_ARRAY_STR); //JSONArray jsonArray1 = JSONArray.parseArray(JSON_ARRAY_STR);//因为JSONArray继承了JSON,所以这样也是可以的 //遍历方式1 int size = jsonArray.size(); for (int i = 0; i < size; i++){ JSONObject jsonObject = jsonArray.getJSONObject(i); System.out.println(jsonObject.getString("studentName")+":"+jsonObject.getInteger("studentAge")); } //遍历方式2 for (Object obj : jsonArray) { JSONObject jsonObject = (JSONObject) obj; System.out.println(jsonObject.getString("studentName")+":"+jsonObject.getInteger("studentAge")); } }
示例1.3-复杂json格式字符串与JSONObject之间的转换
/** * 复杂json格式字符串与JSONObject之间的转换 */ public static void testComplexJSONStrToJSONObject(){ JSONObject jsonObject = JSON.parseObject(COMPLEX_JSON_STR); //JSONObject jsonObject1 = JSONObject.parseObject(COMPLEX_JSON_STR);//因为JSONObject继承了JSON,所以这样也是可以的 String teacherName = jsonObject.getString("teacherName"); Integer teacherAge = jsonObject.getInteger("teacherAge"); JSONObject course = jsonObject.getJSONObject("course"); JSONArray students = jsonObject.getJSONArray("students"); }
示例2:JSON格式字符串与javaBean之间的转换。
首先,我们针对数据源所示的字符串,提供三个javaBean。
public class Student { private String studentName; private Integer studentAge; public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } public Integer getStudentAge() { return studentAge; } public void setStudentAge(Integer studentAge) { this.studentAge = studentAge; } }
public class Course { private String courseName; private Integer code; public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } }
public class Teacher { private String teacherName; private Integer teacherAge; private Course course; private List<Student> students; public String getTeacherName() { return teacherName; } public void setTeacherName(String teacherName) { this.teacherName = teacherName; } public Integer getTeacherAge() { return teacherAge; } public void setTeacherAge(Integer teacherAge) { this.teacherAge = teacherAge; } public Course getCourse() { return course; } public void setCourse(Course course) { this.course = course; } public List<Student> getStudents() { return students; } public void setStudents(List<Student> students) { this.students = students; } }
json字符串与javaBean之间的转换推荐使用 TypeReference<T> 这个类,使用泛型可以更加清晰,当然也有其它的转换方式,这里就不做探讨了。
示例2.1-json字符串-简单对象型与javaBean之间的转换
/** * json字符串-简单对象与JavaBean_obj之间的转换 */ public static void testJSONStrToJavaBeanObj(){ Student student = JSON.parseObject(JSON_OBJ_STR, new TypeReference<Student>() {}); //Student student1 = JSONObject.parseObject(JSON_OBJ_STR, new TypeReference<Student>() {});//因为JSONObject继承了JSON,所以这样也是可以的 System.out.println(student.getStudentName()+":"+student.getStudentAge()); }
示例2.2-json字符串-数组类型与javaBean之间的转换
/** * json字符串-数组类型与JavaBean_List之间的转换 */ public static void testJSONStrToJavaBeanList(){ ArrayList<Student> students = JSON.parseObject(JSON_ARRAY_STR, new TypeReference<ArrayList<Student>>() {}); //ArrayList<Student> students1 = JSONArray.parseObject(JSON_ARRAY_STR, new TypeReference<ArrayList<Student>>() {});//因为JSONArray继承了JSON,所以这样也是可以的 for (Student student : students) { System.out.println(student.getStudentName()+":"+student.getStudentAge()); } }
示例2.3-复杂json格式字符串与与javaBean之间的转换
/** * 复杂json格式字符串与JavaBean_obj之间的转换 */ public static void testComplexJSONStrToJavaBean(){ Teacher teacher = JSON.parseObject(COMPLEX_JSON_STR, new TypeReference<Teacher>() {}); //Teacher teacher1 = JSON.parseObject(COMPLEX_JSON_STR, new TypeReference<Teacher>() {});//因为JSONObject继承了JSON,所以这样也是可以的 String teacherName = teacher.getTeacherName(); Integer teacherAge = teacher.getTeacherAge(); Course course = teacher.getCourse(); List<Student> students = teacher.getStudents(); }
对于TypeReference<T>,由于其构造方法使用 protected 进行修饰,所以在其他包下创建其对象的时候,要用其实现类的子类:new TypeReference<Teacher>() {}
此外的:
1,对于JSON对象与JSON格式字符串的转换可以直接用 toJSONString()这个方法。
2,javaBean与JSON格式字符串之间的转换要用到:JSON.toJSONString(obj);
3,javaBean与json对象间的转换使用:JSON.toJSON(obj),然后使用强制类型转换,JSONObject或者JSONArray。