一、 fastjson简介
fastjson是一个Java语言编写的高性能和通用的JSON序列化和反序列化类库,在阿里巴巴经济体的大力推动下成长为了业内流行的JSON库,具有反序列化飞速、易用性强、准确性高、兼容性好、灵活度高的特点。
Json是一种轻量级的数据交换格式,它具有可读性强、数据格式简洁等特点,被广泛应用于网页开发、移动应用、Web API等场合。fastjson就是Java语言下用于解析json字符串的类库,它提供了丰富的API,可以帮助开发人员轻松解析json字符串。
二、快速入门
1、新建Android项目并在build.gradle文件中添加fastjson库的引用
dependencies {
implementation 'com.alibaba:fastjson:1.2.80'
}
2、在MainActivity.java文件中添加如下代码
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private String jsonStr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
jsonStr = "{\n" +
" \"name\": \"Tom\",\n" +
" \"age\": 21,\n" +
" \"score\": {\n" +
" \"math\": 90,\n" +
" \"english\": 87\n" +
" },\n" +
" \"hobby\": [\n" +
" \"study\",\n" +
" \"write\",\n" +
" \"run\"\n" +
" ]\n" +
"}";
//将Json字符串转换为Java对象
Student student = JSON.parseObject(jsonStr, Student.class);
Log.i("MainActivity", "name=" + student.getName());
Log.i("MainActivity", "age=" + student.getAge());
//获取Json对象
JSONObject jsonObject = JSON.parseObject(jsonStr);
int mathScore = jsonObject.getJSONObject("score").getIntValue("math");
Log.i("MainActivity", "mathScore=" + mathScore);
//获取Json数组
JSONArray jsonArray = jsonObject.getJSONArray("hobby");
for (int i = 0; i < jsonArray.size(); i++) {
String hobby = jsonArray.get(i).toString();
Log.i("MainActivity", "hobby=" + hobby);
}
//将Java对象转换为Json字符串
Student newStudent = new Student("Bob", 23);
String newJsonStr = JSON.toJSONString(newStudent);
Log.i("MainActivity", "newJsonStr=" + newJsonStr);
}
}
3、新建Student.java文件并定义如下Java Bean类
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
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;
}
}
4、运行程序并查看输出结果,效果如下
name=Tom
age=21
mathScore=90
hobby=study
hobby=write
hobby=run
newJsonStr={"age":23,"name":"Bob"}
三、常用API介绍
1、将Json字符串转换为Java对象
String jsonStr = "{\"name\":\"Tom\", \"age\":21}";
Student student = JSON.parseObject(jsonStr, Student.class);
2、将Java对象转换为Json字符串
Teacher teacher = new Teacher("Lily", 35);
String jsonStr = JSON.toJSONString(teacher);
Log.i(TAG, jsonStr);
3、获取JsonObject对象
String jsonStr = "{\"name\":\"Tom\", \"age\":21}";
JSONObject jsonObject = JSON.parseObject(jsonStr);
String name = jsonObject.getString("name");
int age = jsonObject.getIntValue("age");
4、获取JsonArray数组
String jsonStr = "[{\"name\":\"Tom\", \"age\":21},{\"name\":\"Jerry\", \"age\":23}]";
JSONArray jsonArray = JSON.parseArray(jsonStr);
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name");
int age = jsonObject.getIntValue("age");
Log.i(TAG, "name=" + name + ", age=" + age);
}
5、序列化和反序列化null对象
// 将null转化为JSON字符串
String nullJson = JSON.toJSONString(null);
Log.i(TAG, "nullJson=" + nullJson); //null
// 将null值的JSON字符串转化为Object对象
Object nullObject = JSON.parse(nullJson);
Log.i(TAG, "nullObject=" + nullObject); //null
// 将Java对象序列化为JSON字符串
Student student = null;
String studentJson = JSON.toJSONString(student, SerializerFeature.WriteNullStringAsEmpty);
Log.i(TAG, "studentJson=" + studentJson); //{"name":"","age":0,null:null}
// 将JSON字符串反序列化为Java对象
Student newStudent = JSON.parseObject(studentJson, Student.class);
Log.i(TAG, "newStudent.getName()=" + newStudent.getName()); //""
Log.i(TAG, "newStudent.getAge()=" + newStudent.getAge()); //0
Log.i(TAG, "newStudent.getInfo()=" + newStudent.getInfo()); //null
四、使用技巧
1、解析复杂Json对象
String jsonStr = "{\n" +
" \"error\": 0,\n" +
" \"reason\": \"成功\",\n" +
" \"result\": {\n" +
" \"stat\": \"1\",\n" +
" \"list\": [\n" +
" {\n" +
" \"stationno\": \"1\",\n" +
" \"content\": \"好孩子\"\n" +
" },\n" +
" {\n" +
" \"stationno\": \"2\",\n" +
" \"content\": \"天才\"\n" +
" }\n" +
" ]\n" +
" }\n" +
"}";
JSONObject jsonObject = JSON.parseObject(jsonStr);
JSONObject result = jsonObject.getJSONObject("result");
JSONArray jsonArray = result.getJSONArray("list");
List<Station> stationList = new ArrayList<>();
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
Station station = JSON.toJavaObject(obj, Station.class);
stationList.add(station);
}
Log.i(TAG, stationList.toString());
2、序列化和反序列化不同类型的对象
String jsonStr = "{\"name\":\"Tom\",\"value\":50}";
Object obj = JSON.parse(jsonStr);
if (obj instanceof Map) { //反序列化为Map对象
Map<String, Object> map = (Map<String, Object>) obj;
Log.i(TAG, map.get("name").toString() + "-" + map.get("value").toString());
} else if (obj instanceof MyObject) { //反序列化为Java对象
MyObject myObject = (MyObject) obj;
Log.i(TAG, myObject.getName() + "-" + myObject.getValue().toString());
}
MyObject myObject = new MyObject("John", 30);
String jsonText = JSON.toJSONString(myObject);
Log.i(TAG, jsonText); //{"content":["John",30]}
MyObject myObject2 = JSON.parseObject(jsonText, MyObject.class);
Log.i(TAG, myObject2.getName() + "-" +myObject2.getValue().toString());
五、总结
fastjson是Android开发中解析json数据的利器。我们通过上述内容的学习,可以将json字符串快速转化成Java对象,结合快速入门中的示例,使你可以无缝的将Json格式数据序列化和反序列化。
如果你想要更深入了解fastjson库的功能和用法,还可以查看官方文档,用最好的工具解析最好的数据。