I want the Fetch Button to display/list only the values of a and b from the object 1
{ "1": {
"a": "a",
"b": "b",
"2": {"a":"a2",
"b":"b2"
},
"5": {
"a": "a2",
"b": "b2"
}
}
}
I cant figure it out how to fetch it, I tried combining many tutorials even though therre are 100 lines of code
"
try {
URL url = new URL("https://api.npoint.io/ba77aacc0972af3c686a");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null){
data = data + line;
}
if (!data.isEmpty()){
JSONObject jsonObject = new JSONObject(data);
JSONArray one = jsonObject.getJSONArray("1");
userList.clear();
for (int i = 0;i < one.length();i++){
JSONObject values = one.getJSONObject(i);
String a = values.getString("a");
userList.add(a);
String b = values.getString("b");
userList.add(b);
I cant figure it out how to fetch it, I tried combining many tutorials even though therre are 100 lines of code
2
Answers
Are you trying to get all the values of a and b in any levels from the object 1, which means you want to get a list of
[a,b,a2,b2,a2,b2]
from your example json:First, you have to get JSONObject 1, but not JSONArray 1. Then, you could maintain a stack for any JSONObject child in JSONObject 1, and iterate the stack until it is empty. In each iteration, you check if key "a" and "b" is contained in current JSONObject child and push any JSONObject child of the current JSONObject to the stack.
It looks like you’re on the right track with your code, but there are a few modifications that need to be made. Let’s break down the process step by step:
Fetch JSON Data: You are fetching the JSON data correctly using the URL and input stream.
Parsing JSON: You are creating a JSONObject from the fetched data. However, in your JSON structure, the "1" object contains sub-objects "2" and "5", so you should access the "2" object instead of trying to loop through the "1" array.
Here’s how you can modify your code to achieve what you want:
In this code, we access the "2" object within the "1" object, and then we retrieve the values of "a" and "b" from the "2" object. You can replace the comments with your desired implementation, whether it’s displaying these values in the UI or using them for any other purpose.