在 Android 中,JSON(JavaScript Object Notation)是一种常用的数据交换格式,用于客户端与服务器之间的数据传输。
Android 提供了多种方式来处理 JSON 数据,以下是常见的处理方式。
1. 原生 JSON 解析
Android 提供了 org.json
包,用于直接解析 JSON 数据。主要类包括:
JSONObject
:表示 JSON 对象。JSONArray
:表示 JSON 数组。
示例代码:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class NativeJsonExample {
public static void parseJson(String jsonString) {
try {
// 将 JSON 字符串解析为 JSONObject
JSONObject jsonObject = new JSONObject(jsonString);
// 获取简单字段
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
// 也可以使用 optString or optInt
// `optXXX` 方法在键不存在或值为 null 时不会抛出异常,
// 而是返回一个默认值(如 null 或指定的默认值)。
String optName = jsonObject.optString("name", "defaultName");
int optAge = jsonObject.optInt("age", 18);
// 获取嵌套对象
JSONObject address = jsonObject.getJSONObject("address");
String city = address.getString("city");
// 获取数组
JSONArray hobbies = jsonObject.getJSONArray("hobbies");
for (int i = 0; i < hobbies.length(); i++) {
String hobby = hobbies.getString(i);
System.out.println(hobby);
}
System.out.println("Name: " + name + ", Age: " + age + ", City: " + city);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
优点:
- 无需额外依赖库。
- 适合简单的 JSON 数据解析。
缺点:
- 手动解析复杂 JSON 数据时代码冗长。
- 缺乏类型安全,容易出错。
2. Gson
Gson 是 Google 提供的一个轻量级 JSON 库,用于将 JSON 数据与 Java 对象相互转换。它简化了 JSON 的解析和生成过程。
添加依赖:
在 build.gradle
文件中添加:
implementation 'com.google.code.gson:gson:2.8.9'
使用步骤:
- 创建与 JSON 数据结构对应的 Java 类。
- 使用
Gson
类进行序列化(对象转 JSON)和反序列化(JSON 转对象)。
示例代码:
假设 JSON 数据如下:
{
"name": "John",
"age": 30,
"address": {
"city": "New York"
},
"hobbies": ["Reading", "Traveling"]
}
对应的 Java 类:
class Address {
String city;
}
class Person {
String name;
int age;
Address address;
List<String> hobbies;
}
解析 JSON:
import com.google.gson.Gson;
public class GsonExample {
public static void parseJson(String jsonString) {
Gson gson = new Gson();
// 将 JSON 字符串解析为 Java 对象
Person person = gson.fromJson(jsonString, Person.class);
System.out.println("Name: " + person.name);
System.out.println("Age: " + person.age);
System.out.println("City: " + person.address.city);
System.out.println("Hobbies: " + person.hobbies);
}
}
生成 JSON:
public class GsonExample {
public static void generateJson() {
Person person = new Person();
person.name = "John";
person.age = 30;
person.address = new Address();
person.address.city = "New York";
person.hobbies = Arrays.asList("Reading", "Traveling");
Gson gson = new Gson();
// 将 Java 对象转换为 JSON 字符串
String jsonString = gson.toJson(person);
System.out.println(jsonString);
}
}
优点:
- 简化了 JSON 的解析和生成。
- 支持复杂的嵌套结构和泛型。
- 提供注解(如
@SerializedName
)支持字段名映射。
缺点:
- 需要额外的依赖。
- 对于非常大的 JSON 数据,可能会有性能问题。
3. 其他 JSON 库
除了原生解析和 Gson,Android 还支持其他 JSON 库,例如:
- Jackson:功能强大,性能优异,支持流式解析。
- Moshi:Square 公司开发的 JSON 库,支持 Kotlin 和注解。
- Fastjson:阿里巴巴开发的高性能 JSON 库。
示例(使用 Moshi):
implementation 'com.squareup.moshi:moshi:1.14.0'
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
public class MoshiExample {
public static void parseJson(String jsonString) {
Moshi moshi = new Moshi.Builder().build();
JsonAdapter<Person> jsonAdapter = moshi.adapter(Person.class);
try {
Person person = jsonAdapter.fromJson(jsonString);
System.out.println("Name: " + person.name);
} catch (Exception e) {
e.printStackTrace();
}
}
}
4. Android Studio 的 GsonFormat 插件
功能:
- 自动生成与 JSON 数据结构对应的 Java 类。
- 提高开发效率,避免手动编写类。
安装步骤:
- 打开 Android Studio。
- 进入
File > Settings > Plugins
(Mac 上为Preferences > Plugins
)。 - 搜索
GsonFormatPlus
,点击安装。 - 重启 Android Studio。
使用方法:
-
复制 JSON 数据。
-
在 Android Studio 中创建一个新的 Java 类。
-
在类文件中右键,选择
Generate > GsonFormatPlus
,或者Alt
+Insert
键弹出 Generate 弹窗,选择GsonFormatPlus
。
-
粘贴 JSON 数据,点击确定。
-
插件会自动生成与 JSON 数据结构匹配的 Java 类。
总结
方法 | 优点 | 缺点 |
---|---|---|
原生解析 | 无需依赖库,适合简单 JSON | 代码冗长,缺乏类型安全 |
Gson | 简洁易用,支持复杂结构和注解 | 需要依赖库,处理超大 JSON 性能较差 |
Jackson | 性能优异,支持流式解析 | 库较大,学习成本高 |
Moshi | Kotlin 友好,支持注解 | 功能不如 Jackson 全面 |
Fastjson | 高性能,支持多种特性 | 社区支持较少 |
在实际开发中,推荐使用 Gson,并结合 GsonFormat 插件 提高开发效率。