<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.60</version> </dependency>
JSON_OBJ_STR = "{"studentName":"lily","studentAge":12}";
JSON_ARRAY_STR = "[{"studentName":"lily","studentAge":12},{"studentName":"lucy","studentAge":15}]";
COMPLEX_JSON_STR="{"teacherName":"crystall","teacherAge":27,"course":{"courseName":"english","code":1270},"students":[{"studentName":"lily","studentAge":12},{"studentName":"lucy","studentAge":15}]}";
字符串轉json對象:JSONObject jsonObject = JSON.parseObject(JSON_OBJ_STR);
字符串轉json數組:JSONArray jsonArray = JSON.parseArray(JSON_ARRAY_STR);
字符串轉復雜json對象(嵌套):JSONObject jsonObject = JSON.parseObject(COMPLEX_JSON_STR);
獲取嵌套里面的對象:JSONObject innerObject = jsonObject.getJSONObject("xxx");
json字符串轉javaBean:Student student = JSON.parseObject(JSON_OBJ_STR, new TypeReference<Student>() {});
復雜對象同上一樣轉;
javaBean 轉json字符串:String bookjson = JSONObject.toJSONString(book, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullBooleanAsFalse);
上面的SerializerFeature有好多枚舉類型,上面的是null值寫成“”,還有空值不寫進字符串的
SerializerFeature.NotWriteDefaultValue,比如studentName為空的時候,序列化成json字符串就是{"studentAge":"21"},沒有sthdentName