JSON没有值

时间:2019-05-29 13:38:28

标签: java android json

我只想出于测试目的而显示JSON中的值,但实际上什么也没收到。哪里有问题? Utils中的链接肯定是正确的,我已经在浏览器上运行了它,一切都很好。

这是代码

实用程序类

public class WeatherUtils {
public WeatherUtils(){}

public static ArrayList<Weather> getHourlyData (double minTemp, double maxTemp, double currentTemp, double airPressure){

    ArrayList<Weather> weatherList = new ArrayList<>();

    try {
        JSONObject reader = new JSONObject("https://api.openweathermap.org/data/2.5/forecast?q=London,us&units=metric&appid=ID...");
        JSONArray array = reader.getJSONArray("list");
        for (int i = 0; i<array.length(); i++){

            JSONObject secondReader = array.getJSONObject(i);
            JSONObject dataObject = secondReader.getJSONObject("main");
            for (int j = 0; j<dataObject.length(); j++){
                currentTemp = dataObject.getDouble("temp");
                minTemp = dataObject.getDouble("temp_min");
                maxTemp = dataObject.getDouble("temp_max");
                airPressure = dataObject.getDouble("pressure");
            }
            weatherList.add(new Weather(currentTemp,minTemp,maxTemp,airPressure));
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
    return weatherList;
 }
}

MainActivity        将a,b,c,d加倍;

    a = 0.0;
    b = 0.0;
    c = 0.0;
    d = 0.0;

    ArrayList<Weather> weathers = WeatherUtils.getHourlyData(a,b,c,d);
    System.out.println(weathers);

JSON结构

 {
  "cod": "200",
  "message": 0.0074,
  "cnt": 40,
  "list": [
    {
      "dt": 1559131200,
      "main": {
        "temp": 22.1,
        "temp_min": 21.32,
        "temp_max": 22.1,
        "pressure": 1012.31,
        "sea_level": 1012.31,
        "grnd_level": 976.84,
        "humidity": 92,
        "temp_kf": 0.78
      },
      "weather": [
        {
          "id": 500,
          "main": "Rain",
          "description": "light rain",
          "icon": "10d"
        }
      ],
      "clouds": {
        "all": 89
      },
      "wind": {
        "speed": 3.08,
        "deg": 213.025
      },
      "rain": {
        "3h": 0.875
      },
      "sys": {
        "pod": "d"
      },
      "dt_txt": "2019-05-29 12:00:00"
    },
    {

当然,还有更多数据。我发布了一个“块”

该如何解决?

2 个答案:

答案 0 :(得分:0)

好吧,考虑到您只想“测试” json解析,您几乎没有选择,但是让我们来看一个简单的选择。但是首先,我会说要提取解析器并将其放在自己的类/方法中,以便测试变得更加容易,就像这样:

public class WeatherUtils {
public WeatherUtils(){}

public static ArrayList<Weather> getHourlyData (double minTemp, double maxTemp, double currentTemp, double airPressure){

    final ArrayList<Weather> weatherList = new ArrayList<>();

    try {
        final JSONObject response = httpCall();
        weatherList = mapWeatherResponse(response);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return weatherList;
 }

public static List<Weather> mapWeatherResponse(JSONObject reader){
    final ArrayList<Weather> weatherList = new ArrayList<>();
    JSONArray array = reader.getJSONArray("list");
    for (int i = 0; i<array.length(); i++){
        JSONObject secondReader = array.getJSONObject(i);
        JSONObject dataObject = secondReader.getJSONObject("main");
        for (int j = 0; j<dataObject.length(); j++){
            currentTemp = dataObject.getDouble("temp");
            minTemp = dataObject.getDouble("temp_min");
            maxTemp = dataObject.getDouble("temp_max");
            airPressure = dataObject.getDouble("pressure");
        }
        weatherList.add(new Weather(currentTemp,minTemp,maxTemp,airPressure));
    }
}
}

使用junit测试测试响应解析器:

您可以这样创建一个junit测试:

public class WeatherUtilsTest {
    @Test
    public void parserResponseTEst() {
        final List<String> expectedResponse = new ArrayList<>();
        //fill the expectedResponse with the correspondent values

        final String json = "{\n" +
                "  \"cod\": \"200\",\n" +
                "  \"message\": 0.0074,\n" +
                "  \"cnt\": 40,\n" +
                "  \"list\": [\n" +
                "    {\n" +
                "      \"dt\": 1559131200,\n" +
                "      \"main\": {\n" +
                "        \"temp\": 22.1,\n" +
                "        \"temp_min\": 21.32,\n" +
                "        \"temp_max\": 22.1,\n" +
                "        \"pressure\": 1012.31,\n" +
                "        \"sea_level\": 1012.31,\n" +
                "        \"grnd_level\": 976.84,\n" +
                "        \"humidity\": 92,\n" +
                "        \"temp_kf\": 0.78\n" +
                "      },\n" +
                "      \"weather\": [\n" +
                "        {\n" +
                "          \"id\": 500,\n" +
                "          \"main\": \"Rain\",\n" +
                "          \"description\": \"light rain\",\n" +
                "          \"icon\": \"10d\"\n" +
                "        }\n" +
                "      ],\n" +
                "      \"clouds\": {\n" +
                "        \"all\": 89\n" +
                "      },\n" +
                "      \"wind\": {\n" +
                "        \"speed\": 3.08,\n" +
                "        \"deg\": 213.025\n" +
                "      },\n" +
                "      \"rain\": {\n" +
                "        \"3h\": 0.875\n" +
                "      }\n" +
                "    }]\n" +
                "    }";

        final List<String> response = WeatherUtils.mapWeatherResponse(new JSONObject(json));
        assertEquals(expectedResponse, response);
    }
}

您正在执行的JSONObject解析器没有任何问题。您提到在Utils中使用的链接是正确的,在浏览器中测试该链接是否正确,邮递员,失眠了吗?

OBS JSONObject reader = new JSONObject("https://api...");不会获取任何内容,您在这里所做的就是根据给定的JSONObject(即“ https://”)创建一个String。 ...”。要获取数据,您需要实现一些http客户端。这是一个示例https://stackoverflow.com/a/4457526/761668

答案 1 :(得分:0)

您没有从服务器获得响应,而是尝试使用URL初始化JSONObject

要检索它,您应该替换此行:

JSONObject reader = new JSONObject("https://api.openweathermap.org/data/2.5/forecast?q=London,us&units=metric&appid=ID...");

使用以下代码:

HttpURLConnection conn = null;
String data = null;
try {
   conn = (HttpURLConnection) new URL("https://api.openweathermap.org/data/2.5/forecast?q=London,us&units=metric&appid=ID...").openConnection();
   conn.setRequestMethod("GET");
   conn.connect();

   BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
   StringBuilder sb = new StringBuilder();
   String line;
   while ((line = br.readLine()) != null) {
      sb.append(line + "\n");
   }
   br.close();
   data = sb.toString();
} catch (Exception e) {
   // do something
} finally {
   if (conn != null) {
      try {
         conn.disconnect();
      } catch (Exception ex) {
         // do something
      }
   }
}

JSONObject reader = new JSONObject(data);

此代码将从端点检索JSON对象,并将其转换为String对象。然后,您可以使用它创建一个JSONObject