1

First, I tried so many answers already such as:

Expected BEGIN_ARRAY but was BEGIN_OBJECT retrofit2

retrofit error Expected BEGIN_ARRAY but was BEGIN_OBJECT

And more.

Also, I do understand that the error is saying that I am returning json object instead of json array.

But, still nothing work.

I am trying to get WordPress blog post in my Android app. I am using WordPress 5.2.1 and WP REST API plugin

RetrofitArrayApi.java

public interface RetrofitArrayApi {

@GET("wp-json/wp/v2/posts?per_page=100")
Call<List<WPPost>> getPostInfo();
/// to make call to dynamic URL
//  @GET
//  Call<List<WPPost>> getPostInfo(@Url String url);
//

}

Yes, I removed the 'List`

JsonApiDataModel.java

public class JsonApiDataModel {

@SerializedName("media_details")
MediaDetails mediaDetails;

public static String getSourceUrl(String json)  {


    return new Gson().fromJson(json, JsonApiDataModel.class).mediaDetails.sizes.full.sourceUrl;


}

public class MediaDetails {
    @SerializedName("sizes")
    Sizes sizes;
}

public class Sizes {
    // you can use full, medium or thumbnail here!
    @SerializedName("full")
    Full full;
}

public class Full {
    @SerializedName("source_url")
    String sourceUrl;
}

}

Model.java

public class Model {

public static final int IMAGE_TYPE =1;
public String title, subtitle, Image, date;
public int type;

public static final int TEXT_TYPE=0;

public String data;


public Model(int mtype, String mtitle, String msubtitle, String image, String mdate ){

    this.title = mtitle;
    this.date = mdate;
    this.subtitle = msubtitle;
    this.type = mtype;
    this.Image = image;
}

public Model(int mtype){

    this.type = mtype;
}
}

Blog.java

public class Blog extends Fragment {




private ProgressBar progressBar;
private String TAG ="BlogFragment";
private ArrayList<Model> list;
private RecyclerViewAdapter adapter;
private RecyclerView recyclerView;
private LinearLayoutManager mLayoutManager;
private String baseURL = "https://www.myfitbytes.com/";
public static final SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
public static List<WPPost> mListPost;
private boolean loading = true;
private int pastVisiblesItems, visibleItemCount, totalItemCount, PageCount=1, PageCountLock=0;






@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    //LayoutInflater lf = getActivity().getLayoutInflater();
    View view = lf.inflate(R.layout.fragment_blog, container, false);

    //set fragment title
   // getActivity().setTitle("Blog");


    //wordpress blog posts

    recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
    progressBar = (ProgressBar) view.findViewById(R.id.progressBarPosts);

    mLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
    recyclerView.setLayoutManager(mLayoutManager);

    list = new ArrayList<Model>();
    /// call retrofill
    getRetrofit();

    adapter = new RecyclerViewAdapter( list, getActivity());

    recyclerView.setAdapter(adapter);




    return view;



}



public void getRetrofit(){




    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(baseURL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    RetrofitArrayApi service = retrofit.create(RetrofitArrayApi.class);
    Call<List<WPPost>>  call = service.getPostInfo();

    Log.e("hellooo", "Service = "+ service);
    Log.e("hellooo", "retrofit = "+ retrofit);
    Log.e("hellooo", "call = "+ call);

    // to make call to dynamic URL

    // String yourURL = yourURL.replace(BaseURL,"");
    // Call<List<WPPost>>  call = service.getPostInfo( yourURL);

    /// to get only 6 post from your blog
    // http://your-blog-url/wp-json/wp/v2/posts?per_page=2

    // to get any specific blog post, use id of post
    //  http://www.blueappsoftware.in/wp-json/wp/v2/posts/1179

    // to get only title and id of specific
    // http://www.blueappsoftware.in/android/wp-json/wp/v2/posts/1179?fields=id,title



    call.enqueue(new Callback<List<WPPost>>() {



        @Override
        public void onResponse(Call<List<WPPost>> call, Response<List<WPPost>> response) {



            Log.e("blog", " response "+ response.body());

            mListPost = response.body();
            progressBar.setVisibility(View.GONE);
            for (int i=0; i<response.body().size();i++){
                Log.e("main ", " title "+ response.body().get(i).getTitle().getRendered() + " "+
                        response.body().get(i).getId());

                Log.e("main ", " HREF "+ response.body().get(i).getLinks().getWpFeaturedmedia().get(0).getHref() + " "+
                        response.body().get(i).getId());

                Log.e("main ", " Date "+ convertDateToTimeAgo(response.body().get(i).getDate()) + response.body().get(i).getDate().getClass().getSimpleName());

                Log.e("Blog ","Category id or Name - " + response.body().get(i).getLink());



                String tempdetails =  response.body().get(i).getExcerpt().getRendered().toString();
                tempdetails = tempdetails.replace("<p>","");
                tempdetails = tempdetails.replace("</p>","");
                tempdetails = tempdetails.replace("[&hellip;]","");


                list.add( new Model( Model.IMAGE_TYPE, response.body().get(i).getTitle().getRendered(),
                        tempdetails,
                        response.body().get(i).getLinks().getWpFeaturedmedia().get(0).getHref(),convertDateToTimeAgo(response.body().get(i).getDateGmt())));




            }

            adapter.notifyDataSetChanged();

        }

        @Override
        public void onFailure(Call<List<WPPost>> call, Throwable t) {
            Log.e("hellooo", "inside onfail t = "+ t);

        }
    });

}



public static List<WPPost> getList(){
    return  mListPost;
}



//convert date
public String convertDateToTimeAgo(String time) {
    String inputPattern = "yyyy-MM-dd'T'HH:mm:ss";
    String outputPattern = "yyyy-MM-dd HH:mm:ss'Z'";
    SimpleDateFormat inputFormat = new SimpleDateFormat(inputPattern);
    SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern);


    inputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    outputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));


    Date date = null;
    String str = null;

    try {


        date = inputFormat.parse(time);
        str = outputFormat.format(date);


        long dateInMilliSecond = System.currentTimeMillis() - date.getTime();


        str = toDuration(dateInMilliSecond);


    Log.e("Blog - ", "Date " + date);
    Log.e("Blog - ", "Str " + str);
     //        Log.e("Blog - ", "dateInMilliSecond " + dateInMillinSecond);

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



    return str;
}





public static final List<Long> times = Arrays.asList(
        TimeUnit.DAYS.toMillis(365),
        TimeUnit.DAYS.toMillis(30),
        TimeUnit.DAYS.toMillis(1),
        TimeUnit.HOURS.toMillis(1),
        TimeUnit.MINUTES.toMillis(1),
        TimeUnit.SECONDS.toMillis(1) );
public static final List<String> timesString = Arrays.asList("year","month","day","hour","minute","second");

public static String toDuration(long duration) {

    StringBuffer res = new StringBuffer();
    for(int i=0;i< times.size(); i++) {
        Long current = times.get(i);
        long temp = duration/current;
        if(temp>0) {
            res.append(temp).append(" ").append( timesString.get(i) ).append(temp != 1 ? "s" : "").append(" ago");
            break;
        }
    }
    if("".equals(res.toString()))
        return "0 seconds ago";
    else
        return res.toString();
   }





   }

As I mentioned, most of the answers recommend to remove 'List' and I did, but it didn't work.

Thanks,

4
  • post your WPPost class Commented Jun 15, 2019 at 4:43
  • Hey...I re-generate the WPPost class and now it works..Maybe WordPress 5 has something new Commented Jun 15, 2019 at 14:35
  • see my answer stackoverflow.com/a/56586549/8660721 Commented Jun 15, 2019 at 14:42
  • yes, that's the answer. Go ahead and post it so I can mark it as CORRECT! Commented Jun 15, 2019 at 14:48

2 Answers 2

1

use this site to generate a correct response class from json response

Sign up to request clarification or add additional context in comments.

Comments

1

There is an error in your POJO You need to accept as Array but you are accepting as Object.Use this structure hope this helpful to you

 private List<ClassName> responsekey;

2 Comments

Where exactly should i add this line?
You need to add this line in your POJO.Where the response is returned

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.