Gson可以把一段JSON字符串自动映射成一个对象,不需要手动解析
app/build.gradle 添加依赖
implementation 'com.google.code.gson:gson:2.8.9'
基本用法
定义一个Person类,加入name, age字段,使用如下代码可以将JSON数据自动解析为Person对象
Gson gson = new Gson();Person person = gson.fromJson(jsonData, Person.class);
如果是JSON数组,徐娅借助TypeToken将期望解析的数据类型传入到fromJson中
List<Person> people = gson.fromJson(jsonData, new TypeToken<List<Person>>()){}.getType());
实践
定义一个App类, 加入id, name, version字段
public class App {private String id;private String name;private String version;public String getId() {return id;};public void setId(String id) {this.id = id;}public String getName() {return id;};public void setName(String name) {this.name = name;}public String getVersion() {return version;};public void setVersion(String version) {this.version = version;}}
修改MainActivity
4.1 添加解析JSON方法:
private void parseJSONWithGSon(String jsonData) {Gson gson = new Gson();List<App> appList = gson.fromJson(jsonData, new TypeToken<List<App>>(){}.getType());for (App app : appList) {Log.d("MainActivity", "id is" + app.getId());Log.d("MainActivity", "Name is" + app.getName());Log.d("MainActivity", "version is" + app.getVersion());}}
4.2 调用解析方法
OkHttpClient client = new OkHttpClient();Request request = new Request.Builder().url("http://10.90.141.44:3000/json/").build();Response response = client.newCall(request).execute();assert response.body() != null;String responseData = response.body().string();parseJSONWithGSon(responseData);
如果出现错误
java.lang.RuntimeException: .UnknownServiceException: CLEARTEXT communication to localhost not permitted by network security policy
是由于 Android P(API级别29) 是默认禁止访问 http的 API
解决方法:
在AndroidManifest.xml文件appliction节点中添加
android:usesCleartextTraffic="true"
重新编译即可