我正在尝试从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"
}
}
我正在尝试获取"status: 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。
发布于 2019-05-24 03:02:33
您需要使用Gson获取data
对象,然后才能访问它的字段:
int activation_id = jsonObject.get("data").getAsJsonObject().get("activation_id").getAsInt();
发布于 2019-05-24 03:26:10
您使用了两个库来进行JSON解析,这在本文中不是必需的。假设您想要使用Gson
。删除JSONParser jsonParser = new JSONParser();
现在,在您的JSON数据中,可以通过Root -> data -> activation_id
访问activation_id
。根代表存储到jsonObject
中的整个JSON对象。data
密钥本身代表一个对象。因此,我们可以通过将data
键值作为对象来获取activation_id
,然后以整数/字符串的形式获取activation_id
。
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(jsonS, JsonObject.class);
int id = jsonObject.get("status").getAsInt();
int activationId = jsonObject.get("data").getAsJsonObject().get("activation_id").getAsInt();
有关json对象的更多信息:https://www.shapediver.com/blog/json-objects-explained/
https://stackoverflow.com/questions/56281361
复制相似问题