Question

I've been looking for this for a while now, but couldn't find it anywhere in SO or in the docs. I am using Gson to parse a json file, and suppose the file is:

{
    "animal":"cat",
    "paws":"4",
    "eyes":"2"
}

Now, since all the fields are strings, I want to parse it as an array of strings, I want something like:

{"cat","4","2"}

And I would like to parse the JsonObject regardless of the name of its tags, and that's where the problem lies. I can garantee the json will contain only strings, but I have no clue of what the fields are going to be named.

Anyone ever faced this problem ? Any help is much appreciated, and any research direction also.

Edit

From the anwers, I managed to do it like this:

for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
    // do your stuff here
}

as explained in this answer

Was it helpful?

Solution

JSONObject has the keys() method that returns an Iterator<String>. Through the iterator you can retrieve the value associated with each key. Here the documentation

EDIT: Since you are using GSON , you can retrieve the keys through the method entrySet()

OTHER TIPS

You should use Iterator, which you can get by calling .keys() on your JSONObject. I think something like that should work (using org.json library):

String[] output = new String[jsonObject.length()];
Iterator iterator = jsonObject.keys();
int i = 0;
while (iterator.hasNext()){
    output[i++] = jsonObject.optString((String) iterator.next());
}

EDIT Ok, in case of GSON it will be like this:

Set<Map.Entry<String, JsonElement>> set = jsonObject.entrySet();
String[] out = new String[set.size()];
int i = 0;
for (Map.Entry<String, JsonElement> x : set){
    out[i++] = x.getValue().toString();
}

If you are using gson then simple solution is :

Type mapType = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> map = gson.fromJson(YOUR_JSON_STRING, mapType);
// get only values from map
Collection<String> values = map.values();

for (String string : values) {
  // do your stuff here
}

result values collection contains

[cat, 4, 2]
 JSONObject jsonObject = new JSONObject(parentJson.getJSONObject("objectname")
            .toString());
 Iterator<?> iter = jsonObject.keys();
        while (iter.hasNext()) {
  String key =(String) iter.next();
  String value =  jsonObject.getString(key);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top