0

I've a huge json string that I want to use to retrieve objects. That's why I used Gson instead of the usual JsonObject as said here.

Here is my code:

public List<ProductJavaBean> getProductsData()
{
    url = "http://api.xxx/products.json";
    String line = "";
    Gson gson = new GsonBuilder().create();
    List<ProductJavaBean> products = new ArrayList<ProductJavaBean>();

    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet request = new HttpGet();
        URI website = new URI(url);

        request.setURI(website);
        HttpResponse response = httpclient.execute(request);

        JsonReader reader = new JsonReader(new InputStreamReader(response.getEntity().getContent(),"UTF-8"));
        reader.beginArray();    

        while(reader.hasNext())
        {
            ProductJavaBean product = gson.fromJson(reader ,ProductJavaBean.class);
            products.add(product);
        }
        reader.endArray();
        reader.close();
    }
    catch (Exception exc)
    {
        Log.e("Error retrieving products data:" , exc.getMessage());
        exc.printStackTrace();
    }
    return products;
}

as I followed the API samples.

But I have a strange behaviour on the fromJson method:

The method fromJson(String, Class) in the type Gson is not applicable for the arguments (JsonReader, Class)

enter image description here

Thanks.

EDIT:

here are my imports:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.R;
import android.os.AsyncTask;
import android.util.JsonReader;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.gz.constancl.model.ProductJavaBean;
Florent Gz
  • 934
  • 1
  • 10
  • 22

1 Answers1

-1

You can modify ur code from

JsonReader reader = new JsonReader(new InputStreamReader(response.getEntity().getContent(),"UTF-8"));
reader.beginArray();    

while(reader.hasNext())
{
    ProductJavaBean product = gson.fromJson(reader ,ProductJavaBean.class);
    products.add(product);
}
reader.endArray();
reader.close();

to

Type listType = new TypeToken<ArrayList<ProductJavaBean>>() {}.getType();
products  = new Gson().fromJson(EntityUtils.toString(response.getEntity()), listType);
Harsha Vardhan
  • 3,324
  • 2
  • 17
  • 22
  • 1
    There's no need to modify the code. The import `android.util.JsonReader`was just wrong and needed to be changed to `com.google.gson.stream.JsonReader`. That's also why this question was flagged as a duplicate. – reVerse Sep 21 '14 at 09:57