简体   繁体   中英

Expected BEGIN_OBJECT but was BEGIN_ARRAY : Retrofit2 Android

I am new in JSON parsing and trying to parse the following JSON:

[
 {
"id" : 1,
"title" : {
    "rendered": "a link"
 },
"categories": [ 4,9,11 ],
"links":{
        "featuredmedia":[
        {
          "href": link
        }
           ]
    }
},
...
]

My Interface is:

public interface MediaAPI {
    @GET("Media")
    Call<LinkList> getDetails();
}

My model classes are:

public class LinkList {
    private List<Links> links;
    // getter and setter    
}

...

public class Links {
  private List<Featuredmedia> Featured = new ArrayList<Featuredmedia>();
  // getter and setter 
 }

...

public class Featuredmedia {
    private String href;
    // getter and setter    
}

and Client code is:

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(ROOT_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    MediaAPI service = retrofit.create(MediaAPI.class);

    Call<LinkList> call = service.getDetails();
    call.enqueue(new Callback<LinkList>() {
        @Override
        public void onResponse(Call<LinkList> call, Response<LinkList> response) {
            if(response.isSuccessful()){                   
                successToast();
            }
            else {                                      
                failToast();
            }
        }

        @Override
        public void onFailure(Call<LinkList> call, Throwable t) {               
            Log.d("Failed", t.getMessage());
            showToast();

        }
    });

I only need to get the link inside "featuredmedia" so I only included those in the models. I also got some idea about the error from here but the error still there.

Any suggestion how to solve this will be great help.

Change the Links model like this .

public class Links {
  private List<Featuredmedia> featuredmedia = new ArrayList<Featuredmedia>();
  // getter and setter 
 }

And also LinkList should be like this .

public class LinkList {
    private Links links;
    // getter and setter    
}

Gson will take care of Deserializing the json to your LinksList and expects an object for this to work.

Your model basically expects something like :

{
   links: [...]
}

Since your Response Json is an array, you want to have a model representing this: any Array or List will do.

So instead of using LinkList, just use eg Call<List<Links>>

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