读取JSON数据但无法转换为JSONArray

时间:2014-09-05 05:34:14

标签: android json arrays jsonobject

我正在开发一个读取JSON数据的应用程序。解析了Json Data,但它没有在listview中查看。 Logcat说类型不匹配。我对Json并不熟悉。
http://api.openweathermap.org/data/2.5/forecast/daily?lat=6.421465&lon=81.332396&cnt=10&mode=json

这是我的logcat和代码。请麻烦我。

  

org.json.JSONException:索引1超出范围[0..1)   org.json.JSONArray.get(JSONArray.java:263)   org.json.JSONArray.getString(JSONArray.java:421)   com.is.parsej.ParseJ $ GetContacts.doInBackground(ParseJ.java:141)   com.is.parsej.ParseJ $ GetContacts.doInBackground(ParseJ.java:1)   android.os.AsyncTask $ 2.call(AsyncTask.java:287)   java.util.concurrent.FutureTask.run(FutureTask.java:234)   android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:230)   java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)

   public class ParseJ extends ListActivity {

         private ProgressDialog pDialog;

            // URL to get contacts JSON
            private static String url = "http://api.openweathermap.org/data/2.5/forecast/daily?lat=6.421465&lon=81.332396&cnt=10&mode=json";

            // JSON Node names
            private static final String TAG_COd = "list"; //edited
            private static final String TAG_ID = "dt";    //edited

            private static final String TAG_WEATHER = "weather";
            private static final String TAG_MAIN = "main";
            private static final String TAG_DESC = "description";

            private static final String TAG_TEMP = "temp";
            private static final String TAG_DAY = "day";
            private static final String TAG_MIN = "min";
            private static final String TAG_MAX = "max";
            private static final String TAG_NIGHT = "night";
            private static final String TAG_MORN= "morn";

            private static final String TAG_HUMIDITY = "humidity";

            // contacts JSONArray
            JSONArray contacts = null;

            // Hashmap for ListView
            ArrayList<HashMap<String, String>> contactList;

            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_parse_j);

                contactList = new ArrayList<HashMap<String, String>>();

                ListView lv = getListView();

                // Listview on item click listener
                lv.setOnItemClickListener(new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                            int position, long id) {
                        // getting values from selected ListItem
                        String weather = ((TextView) view.findViewById(R.id.main))
                                .getText().toString();
                        String Temp = ((TextView) view.findViewById(R.id.Descrption))
                                .getText().toString();
                        String Humidity = ((TextView) view.findViewById(R.id.temp))
                                .getText().toString();

                        // Starting single contact activity
                        Intent in = new Intent(getApplicationContext(),
                                SingleContactActivity.class);
                        in.putExtra(TAG_WEATHER, weather);
                        in.putExtra(TAG_TEMP, Temp);
                        in.putExtra(TAG_HUMIDITY, Humidity);
                        startActivity(in);

                    }
                });

                // Calling async task to get json
                new GetContacts().execute();
            }

            /**
             * Async task class to get json by making HTTP call
             * */
            private class GetContacts extends AsyncTask<Void, Void, Void> {

                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    // Showing progress dialog
                    pDialog = new ProgressDialog(ParseJ.this);
                    pDialog.setMessage("Please wait...");
                    pDialog.setCancelable(false);
                    pDialog.show();

                }

                @Override
                protected Void doInBackground(Void... arg0) {
                    // Creating service handler class instance
                    ServiceHandler sh = new ServiceHandler();

                    // Making a request to url and getting response
                    String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

                    Log.d("Response: ", "> " + jsonStr);

                    if (jsonStr != null) {
                        try {
                            JSONObject jsonObj = new JSONObject(jsonStr);

                            // Getting JSON Array node
                            contacts = jsonObj.getJSONArray(TAG_COd);

                            // looping through All Contacts
                            for (int i = 0; i < contacts.length(); i++) {
                                JSONObject c = contacts.getJSONObject(i);

                                String id = c.getString(TAG_ID);
                                String humidity = c.getString(TAG_HUMIDITY);

                                // Phone node is JSON Object
                                JSONObject temp = c.getJSONObject(TAG_TEMP);
                                String day = temp.getString(TAG_DAY);
                                String maxTemp = temp.getString(TAG_MAX);
                                String minTemp = temp.getString(TAG_MIN);
                                String morningTemp = temp.getString(TAG_MORN);
                                //edited
                                JSONArray weather = c.getJSONArray(TAG_WEATHER);
                                String main = weather.getString(1);
                                String desc = weather.getString(2); 

                                // tmp hashmap for single contact
                                HashMap<String, String> contact = new HashMap<String, String>();

                                // adding each child node to HashMap key => value
                                contact.put(TAG_ID, id);
                                contact.put(TAG_DAY, day);
                                contact.put(TAG_DESC, desc);
                                contact.put(TAG_HUMIDITY, humidity);

                                // adding contact to contact list
                                contactList.add(contact);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        Log.e("ServiceHandler", "Couldn't get any data from the url");
                    }

                    return null;
                }

                @Override
                protected void onPostExecute(Void result) {
                    super.onPostExecute(result);
                    // Dismiss the progress dialog
                    if (pDialog.isShowing())
                        pDialog.dismiss();
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            ParseJ.this, contactList,
                            R.layout.list_item, new String[] { TAG_DAY, TAG_DESC,
                                    TAG_HUMIDITY }, new int[] { R.id.temp,
                                    R.id.main, R.id.Descrption });

                    setListAdapter(adapter);
                }

            }

        }

4 个答案:

答案 0 :(得分:1)

根据您的JSON,它只是一个元素列表。数组的开头为[,结尾为]。仔细查看您的JSON,您可能会发现某些数组元素有[]

天气只有1个元素

"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}]

因为你正在使用

而超出范围
   JSONArray weather = c.getJSONArray(TAG_WEATHER);
   String main = weather.getString(1);
   String desc = weather.getString(2);

你的json数组天气中没有1和2,因为天气似乎只有1个元素将它放在另一个json对象中

JSONObject weather = c.getJSONArray(TAG_WEATHER).getJSONObject(0);
String main = weather.getString("main");
String desc = weather.getString("description");

答案 1 :(得分:1)

                 JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    contacts = jsonObj.getJSONArray("list");

                    // looping through All Contacts
                    for (int i = 0; i < contacts.length(); i++) {
}

在您的代码中更改此内容,如果有任何问题,请告诉我。

答案 2 :(得分:1)

json在这里

  

{的 “鳕鱼”: “200”下, “消息”:0.2809, “城市”:{ “ID”:1244926, “姓名”: “班托塔”, “坐标”:{” LON “:81.1185,” LAT “:6.1241},” 国家 “:” LK”, “种群”:0}, “CNT”:10, “列表”:[{ “DT”:1409896800, “TEMP”:{ “日”:301.95, “min” 是:300.47, “最大值”:302.12, “夜”:301.31, “前夕”:301.87, “早晨”:300.47}, “压力”:1020.63, “湿度”:88,”天气 “:[{” ID “:803,” 主 “:” 云 “ ”描述“:” 破   云”, “图标”: “04D”}], “速度”:6.47, “DEG”:243, “云”:56},{ “DT”:1409983200, “TEMP”:{ “天”:301.11, “min” 是:299.62, “最大值”:301.29, “夜”:299.62, “前夕”:300.76, “早晨”:300.13}, “压力”:1021.53, “湿度”:92, “天气”:[{” ID “:802,” 主 “:” 云 “ ”说明“:” 散   云”, “图标”: “03D”}], “速度”:6.66, “DEG”:249, “云”:48},{ “DT”:1410069600, “TEMP”:{ “天”:300.9, “min” 是:299.36, “最大值”:300.9, “夜”:299.58, “前夕”:300.2, “早晨”:299.36}, “压力”:1022.25, “湿度”:90, “天气”:[{” ID “:803,” 主 “:” 云 “ ”说明“:” 破   云”, “图标”: “04D”}], “速度”:7.21, “DEG”:242, “云”:80},{ “DT”:1410156000, “TEMP”:{ “天”:299.47, “min” 是:298.71, “最大值”:300.44, “夜”:299.5, “前夕”:299.96, “早晨”:298.71}, “压力”:1023.27, “湿度”:98, “天气”:[{” ID “:802,” 主 “:” 云 “ ”说明“:” 散   云”, “图标”: “03D”}], “速度”:5.83, “DEG”:252, “云”:44},{ “DT”:1410242400, “TEMP”:{ “天”:301.38, “min” 是:297.39, “最大值”:301.38, “夜”:298.36, “前夕”:300.82, “早晨”:297.39}, “压力”:1012.02, “湿度”:0, “天气”:[{” ID “:500,” 主 “:” 雨 “ ”说明“:” 光   雨”, “图标”: “10D”}], “速度”:3.87, “DEG”:250, “云”:76, “雨”:0.38},{ “DT”:1410328800, “TEMP”:{ “日”:301.77, “min” 是:297.49, “最大值”:301.77, “夜”:299.44, “前夕”:301.13, “早晨”:297.49}, “压力”:1011.84, “湿度”:0,”天气 “:[{” ID “:500,” 主 “:” 雨 “ ”说明“:” 光   雨”, “图标”: “10D”}], “速度”:4.88, “DEG”:259, “云”:27, “雨”:0.82},{ “DT”:1410415200, “TEMP”:{ “日”:302.15, “min” 是:299.15, “最大值”:302.15, “夜”:299.43, “前夕”:300.52, “早晨”:299.15}, “压力”:1011.1, “湿度”:0,”天气 “:[{” ID “:500,” 主 “:” 雨 “ ”说明“:” 光   雨”, “图标”: “10D”}], “速度”:6.3, “DEG”:257, “云”:64, “雨”:1.82},{ “DT”:1410501600, “TEMP”:{ “日”:301.52, “min” 是:299.16, “最大值”:301.52, “夜”:299.36, “前夕”:300.59, “早晨”:299.16}, “压力”:1011.05, “湿度”:0,”天气 “:[{” ID “:500,” 主 “:” 雨 “ ”说明“:” 光   雨”, “图标”: “10D”}], “速度”:8.05, “DEG”:257, “云”:50, “雨”:2.38},{ “DT”:1410588000, “TEMP”:{ “日”:301.26, “min” 是:298.74, “最大值”:301.26, “夜”:299.53, “前夕”:300.43, “早晨”:298.74}, “压力”:1010.43, “湿度”:0,”天气 “:[{” ID “:500,” 主 “:” 雨 “ ”说明“:” 光   雨”, “图标”: “10D”}], “速度”:7.69, “DEG”:258, “云”:33, “雨”:1.34},{ “DT”:1410674400, “TEMP”:{ “日”:300.01, “min” 是:298.37, “最大值”:300.01, “夜”:298.48, “前夕”:298.37, “早晨”:298.87}, “压力”:1010.17, “湿度”:0,”天气 “:[{” ID “:501,” 主 “:” 雨 “ ”说明“:” 适度   雨”, “图标”: “10D”}], “速度”:8.36, “DEG”:253, “云”:55, “雨”:8.91}

然后你得到标签“cod”的对象

contacts = jsonObj.getJSONArray(TAG_COd)

“鳕鱼”: “200”

你会得到“200”

如何将“200”转换为JSONArray? 数组结构就像这样 [{ “DT”:1409896800},{ “DT”:1409896800},{ “DT”:1409896800},{ “DT”:1409896800}]

以“[”开头,以“]”

结尾

答案 3 :(得分:0)

例外是自我解释

org.json.JSONException: Value 200 at cod of type java.lang.String cannot be converted to JSONArray

您正在将String转换为JSONArray

contacts = jsonObj.getJSONArray(TAG_COd);
当您将其转换为JSONArray时,

cod是一个字符串

String cod = jsonObj.getJSONString(TAG_COd);