-2

In wordpress an Api I use returns the tags' ids in an odd way, it returns in this ways:

"tags":[50,51,54]

I have never seen any Json that doesn't look like "key":"value", and I got no clue how to parse it... I hope you can help, Thank you!

Update: My bad, the example I posted was not a full json, it looks like that:

{"categories":[2,8],"tags":[50,51,54]}
Asaf
  • 31
  • 8

2 Answers2

0

You can create a class for this json string and parse the json with just one line of code as shown in main method.

public class Example {

    private List<Integer> categories = null;
    private List<Integer> tags = null;

    public List<Integer> getCategories() {
        return categories;
    }

    public void setCategories(List<Integer> categories) {
        this.categories = categories;
    }

    public List<Integer> getTags() {
        return tags;
    }

    public void setTags(List<Integer> tags) {
        this.tags = tags;
    }

    public static void main(String[] args) {
        String str = "{\"categories\":[2,8],\"tags\":[50,51,54]}";
        Example example = new Gson().fromJson(str, Example.class);
        System.out.println(example.getCategories());
        System.out.println(example.getTags());
    }
}

You need to have gson library for this and have this import,

import com.google.gson.Gson;

Hope this works for you.

Pushpesh Kumar Rajwanshi
  • 18,127
  • 2
  • 19
  • 36
0

The [] indicate that the tags are stored as an array. You can use JSONObject.getJSONArray() to access the array as a JSONArray object, then use .getInt() to retrieve the values. For example:

    String jsonString = "{\"categories\":[2,8],\"tags\":[50,51,54]}";
    JSONObject jsonObject = new JSONObject(jsonString);
    JSONArray tagsArray = jsonObject.getJSONArray("tags");
    // Transfer JSONArray to an int[] array.
    int tags[] = new int[tagsArray.length()];
    for (int i=0; i<tagsArray.length(); i++) {
        tags[i] = tagsArray.getInt(i);
    }
Aaron Dunigan AtLee
  • 1,860
  • 7
  • 18