2

I have json:

{
  "id": 1,
  "result": [
    {
      "id": 1,
      "imgUrl": "http://test.com/image.jpg",
      "title": "image"
    },
    {
      "id": 2,
      "imgUrl": "http://test.com/image2.jpg",
      "title": "image2"
    } 
  ],
  "jsonrpc": "2.0"
}

how i can parse internal array, i try default retroif gson parsing using model

public class TestRequest {

    public int id;
    public List<ArrayItems> result;
    public String jsonrpc;    
}

public class Item {

   public int id;
   public String imgUrl;
   public String title;
}

and i have error: Expected BEGIN_OBJECT but was BEGIN_ARRAY. Then i try hand parse

Item[] items = GSON.fromJson(json, Item[].class);

and have error:

Expected BEGIN_ARRAY but was BEGIN_OBJECT.

What do we have to do?

Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
Vladislav Aniskin
  • 319
  • 1
  • 4
  • 10

1 Answers1

3

Main problem is you have a List<Item> in your POJO and you pass Item[].class to the parser, what does not match.

Item[] items = GSON.fromJson(json, Item[].class);
//                                 ↑ here!!!!

Anyway, IMHO this is not the right way you should parse this Json.

  • You have a json response with a main object containing 3 tags (id result and jsonrpc).
  • You created something like a Java POJOs representing this main object (TestRequest)

Soooooooo....

USE IT!

According to this, if you parse main object you will have all json content.

TestRequest data = gson.fromJson(reader, TestRequest.class);

Now, lets test it, to have a friendly output, I override Item::toString() in this way:

class Item {

    public int id;
    public String imgUrl;
    public String title;
    
    @Override
    public String toString() {
        return this.id + "-" + this.title;
    }
}

And I tested using this main method:

final String FILE_PATH      = "C:\\tmp\\38830664.json"; // use your own!!!

Gson gson = new Gson();
JsonReader reader = new JsonReader(new FileReader(FILE_PATH));
TestRequest data = gson.fromJson(reader, TestRequest.class);

for (Item i :data.result)
    System.out.println(i);

OUTPUT:

1-image
2-image2
Community
  • 1
  • 1
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109