Android GSON解析

GSON

Gson 是谷歌官方推出的支持JSON--JavaObject相互转换的Java序列化/反序列化库

使用(解析一段JSON数据)
使用的json数据
1
{"name":"Tom","age":20}
解析
1
2
Gson gson = new Gson();
Person person = gson.from(jsonData,Person.class);
使用(解析一段JSON数组 )
添加依赖
1
implementation 'com.google.code.gson:gson:2.8.6'
使用的json数据

建一个User类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.ccc.networktest;

public class User {
private int id;
private String username;
private String password;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}
}
逻辑处理
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
private void sendRequestWithOkhttp() {
//开启线程来发起网络请求
new Thread(new Runnable() {
@Override
public void run() {
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://192.168.2.150:8080/test.json")
.build();
Response response = client.newCall(request).execute();
String responseData = response.body().string();
//showResponse(responseData);
parseJsonWithGSON(responseData);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}

private void parseJsonWithGSON(String responseData) {
Gson gson = new Gson();
List<User> userList = gson.fromJson(responseData, new TypeToken<List<User>>() {}.getType());
for (User user : userList) {
Log.d("test", "---------------------------------");
Log.d("test", "id is " + user.getId());
Log.d("test", "username is " + user.getUsername());
Log.d("test", "password is " + user.getPassword());
}
}
运行结果

可能遇到的错误

由于这个json文件是我在本地放在Tomcat上的,用的是http 运行时会报错如下

1
communication to 192.168.2.150 not permitted by network security policy
原因

Android P(9)开始,限制了明文流量的网络请求,非加密的流量请求都会被系统禁止掉,如果当前应用的请求是 http 请求,而非https ,这样就会导系统禁止当前应用进行该请求,如果 WebView 的 url 用 http 协议,同样会出现加载失败,https不受影响。为此,OkHttp3 做了检查,所以如果使用了明文流量,默认情况下,在 Android P 版本OkHttp3就抛出异常:CLEARTEXT communication to ” + host + ” not permitted by network security policy

解决

AndroidMainfest.xmlApplication下添加一句android:usesCleartextTraffic="true"即可解决

0%