【问题标题】:How can I change the data type depending on the received data如何根据接收到的数据更改数据类型
【发布时间】:2017-10-13 12:42:34
【问题描述】:

我正在使用 REST api 获取数据。 JSON 行看起来像 "temp_c":12,,我是这样理解的

int temp =  (int) list.get("temp_c");

问题是行可以有 int 或 double 类型(如temp_c":12.5,),我有错误

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Double

如果我使用

double temp =  (double) list.get("temp_c");

我有错误

java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Integer

【问题讨论】:

    标签: android json rest


    【解决方案1】:

    试试这个。

    先改成String,再用Double.parseDouble解析

    String str = list.get("temp_c")+"";
    double temp = Double.parseDouble(str);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-03
      • 1970-01-01
      • 2013-08-31
      • 2020-09-23
      • 1970-01-01
      • 2012-02-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多