【问题标题】:PHP Web Service JSON EncodingPHP Web 服务 JSON 编码
【发布时间】:2016-07-19 07:21:46
【问题描述】:

我正在搞乱并在 php/json 中创建一个 Web 服务。

<?php
    $answer = array('status'=>401, 'answer'=>'');


    if($numWeeks%2 == 0) {
        $answer['answer'] = 'trash';
        utf8_encode($answer['answer']);
        $answer['status'] = 200;
    }
    else {
        $answer['answer'] = 'trach/recycle';
        utf8_encode($answer['answer']);
        $answer['status'] = 200;
    }

    header('Content-type: application/json');
    echo json_encode($answer);
?>

输出:

{"status":200,"answer":"trash"}

我也在尝试通过一个使用 RETROFIT (v1.9) 的 android 应用来阅读这篇文章。

我的对象类是:

public class TrashResponse {

    public int status;
    public String answer;


}

但我得到这个错误:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

根据我的研究,它与我的网络服务中的 json 对象有关。我无法指出问题所在。

【问题讨论】:

    标签: php android json retrofit


    【解决方案1】:

    在您的 TrashResponse 类中,status 是 String 类型,但 json 中的值是 Integer 类型。修改一下再试试看是否有效。

    【讨论】:

    • 它没有工作 :( 我仍然得到同样的错误......我将状态更改为 int 类型并且不工作
    • 你认为这与json编码不是UTF8有关吗?
    【解决方案2】:

    有两种方法可以在服务器端代码中解决这个问题

    <?php
        $answer = array('status'=> "401", 'answer'=>'');
    
    
        if($numWeeks%2 == 0) {
            $answer['answer'] = 'trash';
            utf8_encode($answer['answer']);
            $answer['status'] = "200";
        }
        else {
            $answer['answer'] = 'trach/recycle';
            utf8_encode($answer['answer']);
            $answer['status'] = "200";
        }
    
        header('Content-type: application/json');
        echo json_encode($answer);
    ?>
    

    通过将状态更改为字符串

    你可以在android端改变

    public class TrashResponse {
    
        public int status;
        public String answer;
    }
    

    最好在android端做出改变

    【讨论】:

      【解决方案3】:

      我使用的服务器具有旧版本的 PHP。我切换到具有更新版本的另一台服务器并添加了以下代码:

      header('Content-type: application/json');
      echo json_encode($answer, JSON_FORCE_OBJECT);
      

      这返回了一个有效的 JSON 对象。最初,JSON 无效,因为我的应用程序将 json 对象视为字符串。

      【讨论】:

        猜你喜欢
        • 2014-10-27
        • 1970-01-01
        • 2015-09-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-21
        相关资源
        最近更新 更多