-1

I went through all the questions on stack overflow and various articles,but none of them seem to solve my problem.Please help

{"status":"ok","source":"abc-news-au","sortBy":"top","articles":[{"author":"http://www.abc.net.au/news/5511636","title":"Hope for Waters as Commonwealth to argue Ludlam, Roberts wrongly elected","description":"The Commonwealth will argue only Malcolm Roberts and Scott Ludlam should be found to have been wrongly elected to Parliament, potentially also opening the door for a Larissa Waters return.","url":"http://www.abc.net.au/news/2017-09-26/only-roberts-and-ludlam-wrongly-elected-commonwealth/8990398","urlToImage":"http://www.abc.net.au/news/image/8720606-1x1-700x700.jpg","publishedAt":"2017-09-26T09:10:12Z"},{"author":"http://www.abc.net.au/news/rural/anna-vidot/4592718","title":"New records tipped to fall as Australia braces for second heatwave","description":"Temperature records set on Saturday could fall within days as a heatwave looms, the bureau says.","url":"http://www.abc.net.au/news/2017-09-26/bom-records-will-fall-as-eastern-australia-braces-for-heatwave/8988650","urlToImage":"http://www.abc.net.au/news/image/5197898-1x1-700x700.jpg","publishedAt":"2017-09-26T10:11:00Z"},{"author":"http://www.abc.net.au/news/alle-mcmahon/6883402","title":"The Earth will get a little cooler after Mount Agung erupts. Here's why","description":"When Mount Agung finally erupts in Bali — and experts say it could be any moment — global atmospheric temperatures will drop. But don't get too exited, it will far from reverse global warming.","url":"http://www.abc.net.au/news/2017-09-26/how-volcanic-eruptions-can-affect-world-temperatures-mount-agung/8987770","urlToImage":"http://www.abc.net.au/news/image/8988046-1x1-700x700.jpg","publishedAt":"2017-09-26T09:54:47Z"},{"author":"http://www.abc.net.au/news/jessica-haynes/8462720","title":"What are your legal rights if you make an HR complaint at work?","description":"What are your legal rights if you make a human resources complaint at work? And what should happen if someone makes a complaint against you?","url":"http://www.abc.net.au/news/2017-09-26/what-are-your-legal-rights-if-you-make-a-hr-complaint-at-work/8987296","urlToImage":"http://www.abc.net.au/news/image/8968496-1x1-700x700.jpg","publishedAt":"2017-09-26T03:41:24Z"},{"author":null,"title":"Why Twitter won't ban Trump despite his threatening tweets","description":"US President Donald Trump is effectively given carte blanche by his favourite social media platform to tweet what he likes, after questions are raised about his threatening tone.","url":"http://www.abc.net.au/news/2017-09-26/why-twitter-wont-delete-trumps-threatening-north-korea-tweet/8988388","urlToImage":"http://www.abc.net.au/news/image/8940614-1x1-700x700.jpg","publishedAt":"2017-09-26T09:51:22Z"},{"author":"http://www.abc.net.au/news/ellie--sibson/7553504","title":"Waiting 'to kill someone' my whole life: Court hears alleged killer's confession","description":"A police recording taken from Korean student Eunji Ban's accused killer is played in the Supreme Court in Brisbane, where he confesses to the bashing and being troubled by a demon his whole life.","url":"http://www.abc.net.au/news/2017-09-26/korea-students-injuries-so-horrific-gender-indistinguishable/8989462","urlToImage":"http://www.abc.net.au/news/image/5116560-1x1-700x700.jpg","publishedAt":"2017-09-26T08:29:24Z"},{"author":null,"title":"Former Swans star Barry Hall clobbers opponent in local footy final","description":"Barry Hall is at it again. This time, the former Sydney Swans star clobbers an opponents twice during a local footy grand final in Queensland.","url":"http://www.abc.net.au/news/2017-09-26/barry-hall-caught-striking-two-opponents-in-qafl-grand-final/8990650","urlToImage":"http://www.abc.net.au/news/image/8990710-1x1-700x700.jpg","publishedAt":"2017-09-26T08:37:48Z"},{"author":"http://www.abc.net.au/news/david-chau/8543210","title":"Fears Afterpay's 'instant approvals' will cause serious financial hardship","description":"With Afterpay's increasing popularity, consumer advocates are concerned it will lead to greater financial hardship for customers.","url":"http://www.abc.net.au/news/2017-09-26/afterpay-consumer-debt/8988394","urlToImage":"http://www.abc.net.au/news/image/8988408-1x1-700x700.jpg","publishedAt":"2017-09-26T10:00:55Z"},{"author":null,"title":"Apartment lending rules tightened in Perth, Brisbane as oversupply bites","description":"The ANZ tells its brokers to tighten lending restrictions in 11 postcodes in Brisbane and Perth, where buyers will now need a 20 per cent deposit before they can borrow.","url":"http://www.abc.net.au/news/2017-09-26/anz-tightens-apartment-lending-rules-in-brisbane-and-perth/8987698","urlToImage":"http://www.abc.net.au/news/image/8871160-1x1-700x700.jpg","publishedAt":"2017-09-26T05:31:47Z"},{"author":"http://www.abc.net.au/news/mazoe-ford/6525834, http://www.abc.net.au/news/antonette-collins/6555778","title":"'I love chatting to pedos': Ben McCormack pleads guilty to child porn charges","description":"Ben McCormack could face a maximum of 15 years in jail after pleading guilty over child pornography charges.","url":"http://www.abc.net.au/news/2017-09-26/ben-mccormack-a-current-affair-former-journalist-pleads-guilty/8987272","urlToImage":"http://www.abc.net.au/news/image/8989938-1x1-700x700.jpg","publishedAt":"2017-09-26T07:48:34Z"}]}

This my json

User.java

public class User {

    @SerializedName("status")
    @Expose
    private String status;
    @SerializedName("source")
    @Expose
    private String source;
    @SerializedName("sortBy")
    @Expose
    private String sortBy;
    @SerializedName("articles")
    @Expose
    private List<Article> articles = null;

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }

    public String getSortBy() {
        return sortBy;
    }

    public void setSortBy(String sortBy) {
        this.sortBy = sortBy;
    }

    public List<Article> getArticles() {
        return articles;
    }

    public void setArticles(List<Article> articles) {
        this.articles = articles;
    }

}

Article.java

public class Article {

    @SerializedName("author")
    @Expose
    private String author;
    @SerializedName("title")
    @Expose
    private String title;
    @SerializedName("description")
    @Expose
    private String description;
    @SerializedName("url")
    @Expose
    private String url;
    @SerializedName("urlToImage")
    @Expose
    private String urlToImage;
    @SerializedName("publishedAt")
    @Expose
    private String publishedAt;

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUrlToImage() {
        return urlToImage;
    }

    public void setUrlToImage(String urlToImage) {
        this.urlToImage = urlToImage;
    }

    public String getPublishedAt() {
        return publishedAt;
    }

    public void setPublishedAt(String publishedAt) {
        this.publishedAt = publishedAt;
    }

}

public class GithubAdapter extends RecyclerView.Adapter<GithubAdapter.GithubViewHolder>
{

    private Context context;
    private Article[] data;

    public GithubAdapter(Context context, Article[] data) {
        this.context = context;
        this.data = data;
    }

    @Override
    public GithubViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater=LayoutInflater.from(parent.getContext());
        View view=layoutInflater.inflate(R.layout.list_item,parent,false);
        return new GithubViewHolder(view);
    }

    @Override
    public void onBindViewHolder(GithubViewHolder holder, int position) {
        Article user=data[position];
        holder.textView.setText(user.getTitle());
        Glide.with(holder.imageView.getContext()).load(user.getUrl()).into(holder.imageView);
    }

    @Override
    public int getItemCount() {
        return data.length;
    }

Adapter

    public class GithubViewHolder extends RecyclerView.ViewHolder{
        ImageView imageView;
        TextView textView;
        public GithubViewHolder(View itemView) {
            super(itemView);
            imageView=(ImageView)itemView.findViewById(R.id.imageview);
            textView=(TextView)itemView.findViewById(R.id.textview);
        }
    }
}

MainActivity

public class MainActivity extends AppCompatActivity {

    public static final String GITURL="https://newsapi.org/v1/articles?source=abc-news-au&sortBy=top&apiKey=7379cf7......";
    private RecyclerView recyclerView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView=(RecyclerView)findViewById(R.id.recyclerview);
        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        StringRequest stringRequest=new StringRequest(GITURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                GsonBuilder gsonBuilder=new GsonBuilder();
                Gson gson= gsonBuilder.create();

                Article[] users= gson.fromJson(response,Article[].class);
                recyclerView.setAdapter(new GithubAdapter(MainActivity.this,users));

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(),"Something went wrong",Toast.LENGTH_LONG).show();
            }
        });


        RequestQueue requestQueue= Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }
}

I keep getting Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $. I even tried converting Article to list in Adapter,but it doesn't work.Any help will be appreciated.

FargoArgoCargo
  • 119
  • 1
  • 1
  • 8

4 Answers4

0

According to your json it is an Object. However, you are parsing as if it is an array.

Article[] users= gson.fromJson(response,Article[].class); // here you are treating response as array not an object

correct way of parsing will be

User user = gson.fromJson(response,User.class); 
Kunu
  • 5,078
  • 6
  • 33
  • 61
0

The following line is wrong:

Article[] users= gson.fromJson(response,Article[].class);

It should be

User user = gson.fromJson(response, User.class);

Then you can get the articles with user.getArticles();

Headcracker
  • 522
  • 4
  • 19
0

Try this

User users= gson.fromJson(response,User.class);
 recyclerView.setAdapter(new GithubAdapter(MainActivity.this,users.getArticles());
yogesh lokhande
  • 1,245
  • 1
  • 11
  • 20
0

In your response have object and array both , Create pojo class for object and arrayList.

  1. create a pojo class for your responce(Object first)

    public class Test
    {
    
    private String status, source, sortBy;
    ArrayList<Articles> articles;
    
    public String getStatus() {
    return status;
    }
    
    public String getSource() {
    return source;
    }
    
    public String getSortBy() {
    return sortBy;
    }
    
    public ArrayList<Articles> getArticles() {
    return articles;
    }
    
    
    }
    
  2. create pojo class for ArrayList data

    public class Articles {
    
    private String  author,title,description,url,
    urlToImage,publishedAt;
    public String getAuthor() {
    return author;
    }
    
    public String getTitle() {
    return title;
    }
    
    public String getDescription() {
    return description;
    }
    
    public String getUrl() {
    return url;
    }
    
    public String getUrlToImage() {
    return urlToImage;
    }
    
    public String getPublishedAt() {
    return publishedAt;
    }   
    }
    

In your main Activity After Response do like this

    StringRequest stringRequest=new StringRequest(GITURL, new 
    Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Gson gson = new Gson();
            Test testModel = gson.fromJson(response,Test.class);

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getApplicationContext(),"Something went 
    wrong",Toast.LENGTH_LONG).show();
        }
    });

Hope this will work.

Geeta Gupta
  • 1,622
  • 11
  • 17