-1

There are some other answers to this question on here but not sure how to get them to work with my code.

I have a lot of JSON to pass so I need to stream it rather than do it all at once. I cannot quite get the errors out of the code. Here is my code:

HttpGet request = new HttpGet(getUri + "&"
                + credentials.getOauthStructure());
        HttpResponse response = client.execute(request);

        ICustomerDAO customerDAO = (ICustomerDAO) DAOFactory.getDAO(
                ICustomerDAO.class.getName(), context);
        customerDAO.open();

        Gson gson = new GsonBuilder().serializeNulls()
                .excludeFieldsWithoutExposeAnnotation().create();

        Reader streamReader = new InputStreamReader(response
                .getEntity().getContent());
        JsonReader reader = new JsonReader(streamReader);
        reader.beginArray();

        while (reader.hasNext()) {
            //Do the JSON parsing and data saving here
            Customer customer = gson.fromJson(reader.nextString(), Customer.class);<-----error here
            customerDAO.saveCustomer(customer);
        }
        reader.endArray();
        reader.close();
        customerDAO.close();

I get the error:

Expecting a string but was BEGIN_OBJECT:

On the marked line in the code above.

EDIT: The value of "reader" is "JsonReader near [{"Action":null,"Addr". So Seems to be cut off near the start of the JSON.

I used to get the JSON like this:

HttpGet request = new HttpGet(getUri + "&"
                + credentials.getOauthStructure());
        String content = client.execute(request, new BasicResponseHandler());

But it returned a large amount of json so changed it to the way I currently use, in an attempt to stream it.

Edit 2: My original code was:

public class CustomerSync implements ICustomerSync {
    public static final int QUANTITY = 0;
    private long offset;
    private ProgressDialog progressDialog;
    private Context context;
    private HttpClient client;
    private final String HTTPS_GET_CUSTOMERS = "https://plcloud.c6.ixsecure.com/PLService.svc/GetCustomers";
    private final String GET_URL = "{0}?quant={1}&offset={2}";
    private final String HTTPS_SYNC_CUSTOMERS = "https://plcloud.c6.ixsecure.com/PLService.svc/SyncCustomers";

    private CustomerSync() {
        client = new DefaultHttpClient();
    }

    public CustomerSync(Context context, ProgressDialog progressDialog) {
        this();
        this.context = context;
        this.progressDialog = progressDialog;
    }

    public Customer[] initCustomersFromJson(Credentials credentials)
            throws ClientProtocolException, IOException, URISyntaxException {
        String getUri;
        getUri = MessageFormat.format(GET_URL, HTTPS_GET_CUSTOMERS,
                QUANTITY + "", offset + "");

        credentials.initGetOAuthStructure(HTTPS_GET_CUSTOMERS);

        HttpGet request = new HttpGet(getUri + "&"
                + credentials.getOauthStructure());
        String content = client.execute(request, new BasicResponseHandler());

        Gson gson = new GsonBuilder().serializeNulls()
                .excludeFieldsWithoutExposeAnnotation().create();
        return gson.fromJson(content, Customer[].class);
    }

    @Override
    public void getCustomers(Credentials credentials)
            throws ClientProtocolException, IOException, URISyntaxException {
        ICustomerDAO customerDAO = (ICustomerDAO) DAOFactory.getDAO(
                ICustomerDAO.class.getName(), context);
        customerDAO.open();

        Customer[] customers;

        //do {
            customers = initCustomersFromJson(credentials);
            progressDialog.setMax(customers.length);
            progressDialog.setProgress(0);
            customerDAO.saveCustomers(customers, progressDialog);

            if (customers.length > 0) {
                offset = customers[customers.length - 1].getId();
            }
        //} while (customers.length > 0);

        customerDAO.close();

        Settings.getInstance().setLastSyncCustomerDatetime(new Date());
    }

But that did not stream the data so it caused memory issues.

BeniaminoBaggins
  • 11,202
  • 41
  • 152
  • 287
  • Please show us the `Customer` class along with the JSON you're trying to parse. The error is likely happening because Customer doesn't accurately reflect the JSON format – Cigogne Eveillée Jul 28 '15 at 23:14
  • Print what `reader.nextString()` gives you – Cigogne Eveillée Jul 28 '15 at 23:28
  • @njzk2 It seems to think that is not a valid method of JsonReader – BeniaminoBaggins Jul 28 '15 at 23:40
  • I think you can refer to the `parseRecursive` method [here](https://java.net/nonav/projects/wwt/sources/svn/content/WWT2/src/com/google/gson/Streams.java) – BNK Jul 29 '15 at 01:08
  • you are trying to use 2 different json parser at the same time. can't work. if your issue with your first code is streaming, then why not use `gson.fromJson(content, client.execute(request).getEntity().getContent(), Customer[].class)`? – njzk2 Jul 29 '15 at 01:09

1 Answers1

0

The recommended way to do your http request is as follows:

URL url = new URL(sUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();


String sResult = null;
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
try 
{
    StringBuilder out = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        out.append(line);
    }
    sResult = out.toString();
}   
finally 
{
    // Do cleanup
    try{
        in.close();
        reader.close();
    } catch (IOException e) {
        Log.wtf(AsyncRestHelper.class.getSimpleName(), "Could not close Input Stream!");
        e.printStackTrace();
    }
}

You can then use sResult to parse into Customers with GSON as you're currently doing

Cigogne Eveillée
  • 2,178
  • 22
  • 36
  • Cheers, I have got the JSON in sResult now. However, now at the parsing stage, are you suggesting I do it the way I posted in my "EDIT 2"? Because that is causing memory issues. – BeniaminoBaggins Jul 29 '15 at 00:23
  • @user3935156 You got the JSON in `sResult`, using what? using @Cigogne 's method ? – Darpan Jul 29 '15 at 06:09
  • How is it causing memory issues? Can you post the exact error? Also, let us have a look at your JSON string – Cigogne Eveillée Jul 29 '15 at 16:32