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.
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.
Well you can so :)
String json = "{\"response\": 2}"; int number = Integer.valueOf(json.substring(13, 14)); But why not use GSON or Jackson?
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:
Import libraries:
import org.json.JSONException; import org.json.JSONObject; 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.
Source: https://ru.stackoverflow.com/questions/796803/
All Articles