java - 应为 BEGIN_ARRAY,但在第 1 行第 1 列处为 STRING : getting JSON from PHP to Java with Gson

标签 java php json gson

我的代码有问题。我想从编码 JSON 数组的 PHP 脚本中获取值;

我的 PHP 代码:

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

这是我用于解码 JSON 的 Java 代码:

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

        }

我的类别:

public class Categorie {

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

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

我的问题:

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

如果我理解我的问题,我认为必须解码的 JSON 应该如下所示:

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

但是...为什么它看起来不像没有 '[{...},{...}] ??

如果我在网络浏览器上播放脚本,我会得到[{"id":"1","title":"title1"},{"id":"2","title":"title2"}]

最佳答案

我真的不懂 PHP,但是使用 Java,你可以向你的代码添加一些“调试”,如下所示:

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

        }

    }

您将看到脚本返回的字符串是:

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

当然,这是一个无效的 JSON,因此 Gson 会抛出异常。

关于java - 应为 BEGIN_ARRAY,但在第 1 行第 1 列处为 STRING : getting JSON from PHP to Java with Gson,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23584023/

相关文章:

java - 使用 CachedThreadPool 写入 JTextArea

java - java中的日期格式为DD和dd

php - Yii 中 $model->attributes 和 $model->setAttributes() 的区别

ios - 由于安全问题,无法在 iOS 中打开 HTTP 链接

php - 使用php从mysql获取数据到android

java - 如何检查毫秒时间戳是否在我当前时区的午夜?

java - ProcessBuilder BufferedReader read() 阻塞

php - 从搜索 php 脚本创建错误页面

php - "insert duplicate"执行脚本的两张票

ruby-on-rails - 如何将 ActiveModel::Serializer 与 PostgreSQL JSON 列一起使用