【问题标题】:How can retorfit2 get this json correct?retorfit2 如何正确获取此 json?
【发布时间】:2018-12-07 03:54:28
【问题描述】:

我的 json 字符串生成如下:

    header('Content-type:text/json');
    if (mysql_num_rows ( $result ) != 0) {
        $row = mysql_fetch_assoc($result);
        $jobj=new stdclass();
        foreach($row as $key=>$value){
            $jobj->$key=$value;
        }
    }
    echo json_encode($jobj,JSON_NUMERIC_CHECK);

在浏览器中,结果为{"user_id":1,"step":1,"status":1}

我的 javabean 是:

public class Login {
    private int user_id;
    private int status;
    private int step;

    public Login(int user_id, int status, int step) {
        this.user_id = user_id;
        this.status = status;
        this.step = step;
    }
}

设置...获取...等

当我使用改造 2 时:

instance = new Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl("http://192.168.1.108/")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

我明白了

android.content.res.Resources$NotFoundException: 字符串资源 ID #0x1

当我把 JavaBean 改成这样时:

public class Login {
    private String user_id;
    private String status;
    private String step;


}

我得到了正确的结果。但我想要一个数字,而不是字符串。怎么做?

【问题讨论】:

    标签: java android json gson retrofit2


    【解决方案1】:

    问题不在于 Retrofit 或 JSON。

    当您尝试将文本设置为 TextView 时发生 Resources$NotFoundException。

    如果将整数提供给TextView 的方法setText,它会查找字符串资源,如果找不到则崩溃。

    因此,您应该先将Integer 转换为String,然后再将其设置为TextView

    使用这样的东西:

    textView.setText(String.valueOf(login.user_id));
    

    【讨论】:

      猜你喜欢
      • 2014-12-21
      • 2020-12-07
      • 2018-10-09
      • 2017-08-18
      • 1970-01-01
      • 2015-05-15
      • 1970-01-01
      • 2016-07-07
      • 2011-07-04
      相关资源
      最近更新 更多