How to extract number 2 from an int variable of a JSON response in JAVA? (instead of 2 there can be any multi-digit number)

{ "response": 2 } 

Without the use of third-party libraries.

  • Without the use of third-party libraries - Volodymyr T
  • one
    What is the problem with libraries? - etki
  • @etki, I only need it in the program once and in one place, why download third-party (additional) libraries for this, if you already have AndroidStudio built in - Volodymyr T
  • there is also a built-in grad that does all this downloading for you - etki
  • @etki thanks! I'm still a beginner and did not know this. I thought that if “I didn’t download it myself”, then “this is already built in”) - Volodymyr T

3 answers 3

Well you can so :)

 String json = "{\"response\": 2}"; int number = Integer.valueOf(json.substring(13, 14)); 

But why not use GSON or Jackson?

  • We need a more universal method, because instead of 2 there can be a multi-digit number: 1000, 100 000, etc. - Volodymyr T
  • I need it in the program only once and in one place, why download third-party (additional) libraries for this, if you already have built-in AndroidStudio - Volodymyr T

For example, it is possible to use regulars, but it is also not very universal. If the structure of the answer is different, you will have to cut out the excess with your hands.

Example:

 public static void main(String[] args) { List<String> tmp = new ArrayList<>(); tmp.add("{\"response\": 2}"); tmp.add("{\"response\": 0}"); tmp.add("{\"response\": null}"); tmp.add("{\"response\": 11}"); tmp.add("{\"response\": 111}"); tmp.add("{\"response\": 1111}"); tmp.add("{\"response\": 11111}"); tmp.add("{\"response\": -1111111}"); tmp.forEach(a -> { System.out.println(parseJsonInt(a)); }); } public static Integer parseJsonInt(String json) { Pattern p = Pattern.compile("-?\\d+"); Matcher m = p.matcher(json); while (m.find()) { return Integer.valueOf(m.group()); } return null; } 

    Thanks for the answers, I found the solution to the problem:

    1. Import libraries:

       import org.json.JSONException; import org.json.JSONObject; 
    2. In the right place we write the code:

       int myNumber; try { myNumber = response.json.getInt("response"); } catch (JSONException e) { e.printStackTrace(); } 

      As a result, in the variable myNumber we get our number. Imported libraries are already included in the "kit" AndroidStudio, in addition they do not need to download.