-1

At the line

reader.beginArray();

I get the error:

expected beginarray but was beginobject. 

I tried changing .beginArray() to .beginObject() but it doesn't work.

This code is part of a JsonParser

public List<Noticias> leerArrayNoticias(JsonReader reader) throws IOException {
    ArrayList<Noticias> noticias = new ArrayList<>();
    try {
        reader.beginArray();
        while (reader.hasNext()) {

            noticias.add(leerNoticia(reader));
        }
        reader.endArray();
    }catch(IOException e){
        e.printStackTrace();
    }catch(Exception e){
        e.printStackTrace();
    }
    return noticias;
}

Here is the Json that im trying to parse

{"noticias":
    [    
        {"idnoticias":"109","titulo":"nueva1","descripcion":"nuevo1"},
        {"idnoticias":"110","titulo":"nueva2","descripcion":"nuevo2"}
    ]
}
Paul Roub
  • 36,322
  • 27
  • 84
  • 93

1 Answers1

0

You are reading the JSON wrong, since this JSON contains out of a JSON Object, then a JSON-Array with the key "noticias". So we have to read the JSON like this:

public void readNotes (final JsonReader reader) {
    // MARKING THE FOLLOWING FOR DELETION (SEE BELOW)
    reader.beginObject(); // First start reading the object
    reader.nextName(); // Read the noticias key, we don't need the actual key
    // END MARKING 
    reader.beginArray(); // Start the array of objects

    while (reader.hasNext()) {
        // Start the object and read it out
        reader.beginObject();

        reader.nextName();
        final int idnotes = reader.nextInt();

        reader.nextName();
        final String title = reader.nextString();

        reader.nextName();
        final String description = reader.nextString();

        // Do stuff with the variables

        // Close this object
        reader.endObject();
    }

    reader.endArray(); // Close the array

    // MARKING THE FOLLOWING FOR DELETION (SEE BELOW)
    reader.endObject(); // Close the object
    // END MARKING 
}

However, your JSON could be optimized as we do not need the first object. Then the JSON would be like this:

[    
    {"idnoticias":"109","titulo":"nueva1","descripcion":"nuevo1"},
    {"idnoticias":"110","titulo":"nueva2","descripcion":"nuevo2"}
]

If you have this JSON you can leave out the marked rules as above to make it work.

engineercoding
  • 832
  • 6
  • 14