androidjsongsonjsonreader

JsonReader don't parse correctly String Array


I'm using JsonReader from gson, for parsing JSON, my JSON parsing is fine for all value except this one :

  "tags": [
        "String1",
        "String2",
        "String3",
        "String4"
    ],

This is the code for parsing

 if(key.equals("tags")) {
 try {
        in.beginArray();

        List<String> tags = new ArrayList();

        while (in.hasNext()) {

            String value = in.nextString();
            tags.add(value);
        }

        item.setTags(tags);
        in.endArray();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

in is the JsonReader object, and item is the object where I store the result.

I don't understand why but when this line is done in.beginArray(); the in.hasNext() is sometimes true only once and sometimes not true at all. So I get only the first item of the list or nothing.

Is the format of the Array is correct ? If I use JSONLint for validate the all JSON he say that the JSON is correct


Solution

  • You can try this below code:

    String jsonArrayString = obj.getJSONArray("tags").toString();
                            Gson googleJson = new Gson();
                            List tag = googleJson.fromJson(jsonArrayString, ArrayList.class);
    
                            System.out.println(tag);
                            item.setTags(tag);