There is such a code to get the string value:

json = response.toString(); JsonObject statsObj = parser.parse(json).getAsJsonObject(); JsonElement stats = statsObj.get("status"); String status = stats.toString(); System.out.println(status); 

The status value is a string. When I try to get any other numeric value, I get a NullPointerException error:

 response.toString(); JsonObject statsObj = parser.parse(json).getAsJsonObject(); JsonElement stats = statsObj.get("last_battle_time"); int lbt = stats.getAsInt(); System.out.println(lbt); 

Tell me how to change the parser code for numeric values?


JSON structure

 { "status": "ok", "meta": { "count": 1 }, "data": { "36791942": { "last_battle_time": 1435324597, "account_id": 36791942, "created_at": 1419093115, "updated_at": 1436952967, // ... другие поля... } } } 
  • Do you get an NPE when calling the stats.getAs*() methods? - Nofate
  • Yes. If the value of the element is a string, then everything is fine - Yalikesifulei
  • If you get NPE when calling stats.getAsInt() , then stats == null , then statsObj.get("last_battle_time") returned null . Show the value of the json variable. - Nofate
  • @Nofate pastebin.com/qvGcuk1Y - Yalikesifulei

1 answer 1

At the top level in your json there is no last_battle_time field, that's why you get null . You first need to pull out data from statsObj , then 36791942 and already from it last_battle_time .

 String json = "{\n" + " \"status\": \"ok\",\n" + " \"meta\": {\n" + " \"count\": 1\n" + " },\n" + " \"data\": {\n" + " \"36791942\": {\n" + " \"last_battle_time\": 1435324597,\n" + " \"account_id\": 36791942,\n" + " \"created_at\": 1419093115,\n" + " \"updated_at\": 1436952967\n" + " }\n" + " }\n" + "}"; int id = 36791942; JsonObject statsObj = new JsonParser().parse(json).getAsJsonObject(); JsonObject dataObj = statsObj.getAsJsonObject("data"); JsonObject playerObj = dataObj.getAsJsonObject(Integer.toString(id)); long lbt = playerObj.get("last_battle_time").getAsLong(); System.out.println(lbt); 
  • Got it. But 36791942 is a variable Account ID, information about which is displayed. What then is needed in the fourth line in brackets after .getJsonObject ? There is a variable with the ID itself, but the .getJsonObject(id) option does not work. And there is no GSON .getAsJsonObject () method in GSON, as far as I know. - Yalikesifulei
  • Updated code works. - Nofate