A
A
Andrey Makarkin2018-04-25 14:15:17
Android
Andrey Makarkin, 2018-04-25 14:15:17

How to return keys from an array?

Faced such a problem. We have JSONObject. We have the following array in it:

{
"12":"value1",
"27":"value2",
"85":"value3",
"34":"value4"
}

The point is that
1. array keys can be different (they are not known in advance)
2. the number of keys/values ​​can be different.
How to get values ​​(value1, value2, value3...)?
I know that there is a static method:
JSONObject jsonObject = new JSONObject("{"petr":"Петр","ivan":"Иван"}");
 String[] jsonNames = jsonObject.getNames();

Having received an array of names, it would be possible to go through the cycle and get the values. But my getNames is colored red. I get a hint: Cannot resolve method 'getNames()'

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Makarkin, 2018-04-25
@shotlandec2

the question solved like this:
First put this somewhere:

private <T> Iterable<T> iteratorToIterable(final Iterator<T> iterator) {
    return new Iterable<T>() {
        @Override
        public Iterator<T> iterator() {
            return iterator;
        }
    };
}

Then just iterate over the object's keys and values:
for (String key : iteratorToIterable(object.keys())) {
    JSONObject entry = object.getJSONObject(key);
    // ...

E
Elmo Sputterspark, 2018-04-25
@Sputterspark

Cognitive numero uno fact: This data structure is not called an array.
En segundo, you can simply:

for (String key : jsonObject.keys()) {
    String value = jsonObject.getString(key);
}

There is no getNames(), there is names()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question