简体   繁体   中英

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM