JSON IOException 错误每日预报没有值

JSON IOException error No value for Daily Forecast

我正在为我的应用程序构建一个天气模块我正在使用 accuweather api 来获取 5 天的预报详细信息。我在 manifest.xml.I 中添加了互联网权限,试图获取日志以获取天气 URL,当我单击 url 时,它会在浏览器中打开并显示 json 文件。这意味着 link 是正确的。但是当我创建一个 json 对象并尝试将数据作为 JSON 数组获取时,它显示没有数据: 这是我的代码: MyWeatherActivity.java

public class MyWeather extends AppCompatActivity {
    private final  String TAG = "hello";

    // TODO : If following are not used in activity then move the declaration to asynch task
    private ArrayList<Weather> weatherArrayList = new ArrayList<>();
    private ArrayList<String> dateArray = new ArrayList<>();
    private ArrayList<String> minTempArray = new ArrayList<>();
    private ArrayList<String>maxTempArray= new ArrayList<>();
    private ArrayList<String> backgroundDayArray= new ArrayList<>();
    private ArrayList<String>backgroundNightArray= new ArrayList<>();

    ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_weather);

        findViews();
    }

    protected void findViews()
    {
        listView = findViewById(R.id.list_item1);
        startFetchWeatherDetailsAsyncTask();
    }

    protected void startFetchWeatherDetailsAsyncTask()
    {
        URL weatherUrl= NetworkUtils.buildURLForWeather();
        new FetchWeatherDetails().execute(weatherUrl);
        Log.d(TAG,"oncreate:weatherURL : " + weatherUrl);
    }

    // TODO : Please make below class static and pass all the list in execute parameters
    // TODO : Not doing it will cause the memory leak and you should not access activity objects directly.
    private class FetchWeatherDetails extends AsyncTask<URL,Void,String>{

        @Override
        protected void onPreExecute(){
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(URL... urls) {
            URL weatherUrl =urls[0];
            String weatherSearchResults=null;
            try {
                weatherSearchResults=NetworkUtils.getResponseFromHttpUrl(weatherUrl);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return weatherSearchResults;
        }

        @Override
        protected void onPostExecute(String weatherSearchResults) {
            if(weatherSearchResults !=null && !weatherSearchResults.equals("")){
                weatherArrayList =parseJSON(weatherSearchResults );

            }
            super.onPostExecute(weatherSearchResults);
        }

        private ArrayList<Weather> parseJSON(String weatherSearchResults) {
            if(weatherArrayList!=null){
                weatherArrayList.clear();
            }
            if(weatherSearchResults!=null){
                try {
                    JSONObject rootObject= new JSONObject(weatherSearchResults);
                    **JSONArray results= rootObject.getJSONArray("Daily Forecasts");**
                    // TODO : pass the context in constructor and use weakreference
                    Toast.makeText(getApplicationContext(),"toast:"+results,Toast.LENGTH_LONG).show();
                    for(int i= 0;i<results.length();i++){
                        Weather weather= new Weather();
                        JSONObject resultObj = results.getJSONObject(i);
                        String date = resultObj.getString("date");
                        dateArray.add(date);
                        weather.setDate(date);
                        JSONObject temperatureObj = resultObj.getJSONObject("Temperature");
                        String minTemp=temperatureObj.getJSONObject("Minimum").getString("Value");
                        minTempArray.add(minTemp);
                        weather.setMinTemp(minTemp);
                        String maxTemp=temperatureObj.getJSONObject("Maximum").getString("Value");
                        maxTempArray.add(maxTemp);
                        weather.setMaxTemp(maxTemp);
                        JSONObject backDayObj= resultObj.getJSONObject("Day");
                        String backday=backDayObj.getJSONObject("IconPhrase").getString("");
                        backgroundDayArray.add(backday);
                        weather.setBackgroundDay(backday);
                        JSONObject backNightObj =resultObj.getJSONObject("Night");
                        String backnight =backNightObj.getJSONObject("IconPhrase").getString("");
                        backgroundNightArray.add(backnight);
                        weather.setBackgroundNight(backnight);
                        weatherArrayList.add(weather);

                    }
                    if(weatherArrayList !=null){
                        WeatherAdapter weatherAdapter = new WeatherAdapter(MyWeather.this,weatherArrayList);
                        listView.setAdapter(weatherAdapter);
                    }else {
                        Toast.makeText(getApplicationContext(),"Data invalid",Toast.LENGTH_LONG).show();
                    }
                    return weatherArrayList;

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

A class 对于 getter setter

public class Weather
{
    private String date;
    private String minTemp;
    private String maxTemp;
    private String backgroundDay;
    private String backgroundNight;

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getMinTemp() {
        return minTemp;
    }

    public void setMinTemp(String minTemp) {
        this.minTemp = minTemp;
    }

    public String getMaxTemp() {
        return maxTemp;
    }

    public void setMaxTemp(String maxTemp) {
        this.maxTemp = maxTemp;
    }

    public String getBackgroundDay() {
        return backgroundDay;
    }

    public void setBackgroundDay(String background) {
        this.backgroundDay = background;
    }

    public String getBackgroundNight() {
        return backgroundNight;
    }

    public void setBackgroundNight(String backgroundNight) {
        this.backgroundNight = backgroundNight;
    }
}

连接:

package com.example.a49ersense;

import android.net.Uri;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;

public class NetworkUtils {
    private final static  String WeatherDB_Base_URL=
            "https://dataservice.accuweather.com/forecasts/v1/daily/5day/location key which I have deleted";
    private final static  String API_KEY="my api key which i have deleted";
    private final static  String PARAM_API_KEY="apikey";
    private static final String TAG="hello";
    public static URL buildURLForWeather(){
        Uri builtUri = Uri.parse(WeatherDB_Base_URL).buildUpon()
                .appendQueryParameter(PARAM_API_KEY,API_KEY)
                .build();
        URL url = null;
        try {
            url= new URL(builtUri.toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        Log.d(TAG,"buildUrlForWeather:url:"+url);
        return url;
    }
    public  static String getResponseFromHttpUrl(URL url)throws IOException{
        HttpURLConnection httpURLConnection =(HttpURLConnection) url.openConnection();
        try {
            InputStream in= httpURLConnection.getInputStream();
            Scanner scanner = new Scanner(in);
            scanner.useDelimiter("\A");

            boolean hasInput = scanner.hasNext();
            if(hasInput){
                return scanner.next();
            }else {
                return null;
            }
        }finally {
            httpURLConnection.disconnect();
        }
    }
}

错误是:

W/System.err: org.json.JSONException: No value for Daily Forecasts

您正在使用 每日预测,这是错误的键。您应该使用 DailyForecasts

使用

JSONArray results = rootObject.getJSONArray("DailyForecasts");

而不是

JSONArray results = rootObject.getJSONArray("Daily Forecasts");