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)
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;