java - 在 Java 中使用 Gson 解析来自 HTTP 请求的 JSON 响应
问题描述
我正在尝试从 URL 读取以下 json 输出
{
"error": false,
"status": 200,
"message": "License Key activated successfully.",
"data": {
"expire": 1582657054,
"activation_id": 1519628117,
"expire_date": "2020-02-25 18:57",
"timezone": "UTC",
"the_key": "Cqu62al903ICv40am9nM68Y7o9-32",
"url": "http://domain/my-account/view-license-key/?key=test-32",
"has_expired": false,
"status": "active",
"allow_offline": true,
"offline_interval": "days",
"offline_value": 1,
"downloadable": {
"name": "v1.1.5",
"url": "https://domain/product-1.1.5.zip"
},
"ctoken": "dsfejk8989"
}
}
我正在尝试获取两个值“状态:200”和“activation_id”。
我试过在线查找和解析。似乎没有任何效果。我对整个 json 阅读有点陌生。
try {
JSONParser jsonParser = new JSONParser();
String jsonS = "";
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
jsonS += inputLine;
}
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(jsonS, JsonObject.class);
int id = jsonObject.get("status").getAsInt();
cintout(id);
cout(link);
cout(inputLine);
try {
if (id == 200)
return ValidationType.VALID;
else
return ValidationType.WRONG_RESPONSE;
} catch (IllegalArgumentException exc) {
if (id == 200)
return ValidationType.VALID;
else
return ValidationType.WRONG_RESPONSE;
}
} catch (IOException e) {
e.printStackTrace();
return ValidationType.VALID;
}
我设法检索了状态值,但没有检索到激活 ID。
解决方案
您需要先data
使用 Gson 获取对象,然后才能访问其字段:
int activation_id = jsonObject.get("data").getAsJsonObject().get("activation_id").getAsInt();
推荐阅读
- python - 如何使用 groupby 按日历月显示标准偏差并绘制它?
- angular - Angular8 中的动态渲染
- laravel-5 - 完整性约束违规:1052 列“主题”在 where 子句中不明确
- php - LARAVEL 如何从公共文件夹中删除图像?
- common-lisp - 为 Peter Seibel 的 defclass 宏使用引用的插槽列表
- c - 仅获取文件中每一行的第一个数字
- .net - 逻辑应用中 Google Drive 连接器的动态登录
- html - 有没有办法在 Go 中复制 HTML 标记器?
- javascript - Firebase functions.auth.user().onCreate 没有触发
- oracle - 人力资源数据库总是锁定?