Expected BEGIN_ARRAY but was STRING at line 1 column 1: getting JSON from PHP to Java with Gson

StackOverflow https://stackoverflow.com/questions/23584023

  •  19-07-2023
  •  | 
  •  

Question

I have a problem with my code. I want to get value from a PHP script which encodes a JSON array;

my PHP code :

<?php
$roro = array();
$roro[]  = array(
      'id' => '1',
      'title' => 'title1'
   );
$roro[] = array(
      'id' => '2',
      'title' => 'title2'
   );
$out = array_values($roro);
 echo json_encode($out);
?>

Here my Java code to decode JSON:

    HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://www.liliandgizmo.legtux.org/lilyCreation/getCategorie.php");
        // post.setEntity(new UrlEncodedFormEntity(validateMessage(m)));

        HttpResponse response = client.execute(post);
        StatusLine status = response.getStatusLine();

        if (status.getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();
            final Gson gson = new GsonBuilder().create();
            try {
                Reader read = new InputStreamReader(is);

                mList = gson.fromJson(read, new TypeToken<List<Categorie>>() {
                }.getType());
                is.close();

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

        }

my Categorie class :

public class Categorie {

/**
 * Identifiant en DB.
 */
private int id;

/**
 * Nom de la catégorie.
 */
private String title;
    // + getter & setter
}

my problem :

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 1
    at com.google.gson.Gson.fromJson(Gson.java:815)
    at com.google.gson.Gson.fromJson(Gson.java:768)
    at fr.gizmoichitzo.loisirsaurelie.upload.shared.LoisirGetCategory.test(LoisirGetCategory.java:50)
    at fr.gizmoichitzo.loisirsaurelie.upload.client.Main.main(Main.java:22)
Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 1
    at com.google.gson.stream.JsonReader.beginArray(JsonReader.java:338)
    at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:79)
    at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:60)
    at com.google.gson.Gson.fromJson(Gson.java:803)
    ... 3 more

If I understand my problem, I think the JSON which have to be decode should look like :

'[{...},{...}]'

but ... why it does not look like [{...},{...}] without ' ??

If I play the script on webbrowser I get [{"id":"1","title":"title1"},{"id":"2","title":"title2"}]

Was it helpful?

Solution

I really do not know PHP, but with Java you can add some "debug" to your code like this:

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://www.liliandgizmo.legtux.org/lilyCreation/getCategorie.php");
        // post.setEntity(new UrlEncodedFormEntity(validateMessage(m)));

        HttpResponse response = client.execute(post);
        StatusLine status = response.getStatusLine();

        if (status.getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();

            final Gson gson = new GsonBuilder().create();
            try {
                Reader read = new InputStreamReader(is);

                BufferedReader in = new BufferedReader(read); //added
                String inputLine; //added
                while ((inputLine = in.readLine()) != null) //added
                    System.out.println(inputLine); //added
                in.close(); //added

                //List<Categorie> mList = gson.fromJson(read, new TypeToken<List<Categorie>>() {
                }.getType());
                is.close();

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

        }

    }

and you'll see that the returned string from your script is:

[{"id":"1","title":"title1"},{"id":"2","title":"title2"}]

Of course, this is an invalid JSON so Gson do its job throwing an exception.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top