JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,也易于机器解析和生成。在Android开发中,解析来自REST API的JSON响应是常见的任务。
Android中有几种主要的JSON解析方式:
try {
JSONObject jsonObject = new JSONObject(jsonString);
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
JSONArray hobbies = jsonObject.getJSONArray("hobbies");
for (int i = 0; i < hobbies.length(); i++) {
String hobby = hobbies.getString(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
首先添加依赖:
implementation 'com.google.code.gson:gson:2.8.9'
使用示例:
public class User {
private String name;
private int age;
private List<String> hobbies;
// getters and setters
}
Gson gson = new Gson();
User user = gson.fromJson(jsonString, User.class);
添加依赖:
implementation 'com.squareup.moshi:moshi:1.13.0'
使用示例:
val moshi = Moshi.Builder().build()
val jsonAdapter = moshi.adapter(User::class.java)
val user = jsonAdapter.fromJson(jsonString)
public interface ApiService {
@GET("user/{id}")
Call<User> getUser(@Path("id") int userId);
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService service = retrofit.create(ApiService.class);
Call<User> call = service.getUser(123);
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
if (response.isSuccessful()) {
User user = response.body();
}
}
@Override
public void onFailure(Call<User> call, Throwable t) {
t.printStackTrace();
}
});
原因:JSON格式不正确或字段类型不匹配
解决:
原因:大数据量解析耗时
解决:
原因:JSON中可能缺少某些字段
解决:
解决:
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd HH:mm:ss")
.create();
示例Kotlin协程实现:
suspend fun fetchUser(userId: Int): User? {
return withContext(Dispatchers.IO) {
try {
val response = apiService.getUser(userId)
if (response.isSuccessful) response.body() else null
} catch (e: Exception) {
null
}
}
}
通过以上方法,您可以高效地在Android应用中解析JSON响应并与REST API交互。