Android-Kotlin:发送非空的jsonObject但接收到空的jsonObject

时间:2018-12-17 10:33:19

标签: php android json kotlin

我正在从php文件发送一个json,以便通过android studio中的kotlin代码接收。 在发送之前,我将json写入文件“ test.txt”,执行后该文件的内容为:

test.txt

{"resultarray":{"result":115}}

php 文件的一部分如下

$response = array('result' => 115);     
$response1 = array('resultarray' => $response);
$encoded = json_encode($response1);
file_put_contents("test.txt",$encoded);
header('Content-type: application/json');
exit($encoded);

我正在使用的 Post 类如下:

class Post {

@SerializedName("resultarray")
@Expose
public var resultarray: JSONObject? = null


override fun toString(): String {
   if (resultarray == null )
    {
        return " 'resultarray' is null"

    }else {
        val entries = resultarray?.keys() 
        if (entries == null) {
            return " 'entries' is null"
        }else {
            var tostr = "start"
            for (entry in entries) {
                var whatweget  = resultarray?.get(entry)
                if(whatweget != null) {
                    tostr += " " + whatweget
                }
            }
            return tostr + "end"
        }
    }

执行以上代码段时,结果字符串为

startend

我不知道如何获取“结果”字段,该字段等同于了解如何从jsonobject内部获取jsonobject。 结果数组也等于“ {}”。因此问题可能出在 resultarray 的注释上。

预先感谢

1 个答案:

答案 0 :(得分:1)

此问题的解决方法是将 resultarray 声明为 JSONElement (如下所示)。

class Post {
@SerializedName("resultarray")
@Expose
public var resultarray: JsonElement? = null

    override fun toString(): String {
        return ""+resultarray;
    }
}

当调用toString()时,我将其作为输出:

{"result":115}