2014-09-05 61 views
0

我正在开发一个读取JSON数据的应用程序。 Json数据被解析,但它不在列表视图中查看。 Logcat说关于类型不匹配。我在Json中并不那么熟悉。
http://api.openweathermap.org/data/2.5/forecast/daily?lat=6.421465&lon=81.332396&cnt=10&mode=jsonJSON数据被读取但不能转换为JSONArray

这是我的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); 
       } 

      } 

     } 
+0

检查数据是否有效JSONArray或没有...在JSONArray初始化之前记录您的数据......... – 2014-09-05 05:36:39

+0

是的,整个数据传递给LogCat。之后只发生这种异常。 – Isuru 2014-09-05 05:38:11

回答

1

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

天气只是因为你正在使用

JSONArray weather = c.getJSONArray(TAG_WEATHER); 
    String main = weather.getString(1); 
    String desc = weather.getString(2); 

那里是你的JSON数组的天气没有1和2,由于天气似乎也有1元

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

索引越界只有1个元素将其放入另一个json对象中

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

感谢您的意见 – Isuru 2014-09-05 06:06:59

+0

@Isuru更新了答案 – 2014-09-05 06:15:14

+0

非常感谢。明白了吧。并了解了Json。再次感谢。 – Isuru 2014-09-05 06:20:26

0

例外是自我解释

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

要转换StringJSONArray这里,

contacts = jsonObj.getJSONArray(TAG_COd); 

cod是一个字符串,当你将其转换为JSONArray

String cod = jsonObj.getJSONString(TAG_COd); 
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++) { 
} 

在你的代码中改变这个,并让我知道,如果有任何问题。

+0

我编辑了代码。这是给阵列outOfRange异常 – Isuru 2014-09-05 06:05:00

1

的JSON是这里

{“鳕鱼”: “200”, “消息”:0.2809, “城市”:{ “ID”:1244926, “名”: “汉班托塔”, “坐标”:{ “LON”:81.1185, “LAT”:6.1241}, “国家”: “LK”, “种群”:0}, “CNT”:10, “列表”:[{ “DT”:1409896800 “温度”:{ “天”:301.95, “分”:300.47, “最大”:302.12, “夜”:301.31, “EVE”:301.87, “早晨”:300.47}, “压力”:1020.63,”湿度“:88,”天气“:[{”id“:803,”main“:”云“,”描述“:”破损 云“,”图标“:”04d“}],”速度“:6.47 “度”:243, “云”:56},{ “DT”:1409983200, “TEMP”:{ “天”:301.11, “min” 是:299.62, “最大值”:301.29, “夜”:299.62, “EVE”: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, “主”: “云”,“描述“:”broken“ clouds”,“icon”:“04d”}],“speed”:7.21,“deg”:242,“clouds”:80},{“dt”:1410156000,“temp”:{日 “:299.47,” min “是:298.71,” 最大值 “:300.44,” 夜 “:299.5,” 前夕 “:299.96,” 早晨 “:298.71},” 压力 “:1023.27,” 湿度 “:98,” 天气“:”{“id”:802,“main”:“Clouds”,“description”:“scattered clouds”,“icon”:“03d”}],“speed”:5.83,“deg”:252, “云”:44},{ “DT”:1410242400, “温度”:{ “天”:301.38, “分”:297.39, “最大”:301.38, “夜”:298.36, “EVE”:300.82,” ,“压力”:1012.02,“湿度”:0,“天气”:[{“id”:500,“main”:“雨”,“描述”:“光 雨”,“ “:” 10D “}],” SP EED “: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,“度”:259,“云”:27,“雨”:0.82}, { “DT”:1410415200, “温度”:{ “天”:302.15, “分”:299.15, “最大”:302.15, “夜”:299.43, “EVE”:300.52, “早晨”:299.15},”压力“:1011.1,”湿度“:0,”天气“:[{”id“:500,”main“:”Rain“,”description“:”light rain“,”icon“:”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,”度“: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,” 主 “:” 雨”, “description”:“light rain”,“icon”:“10d”}],“speed”:7.69,“deg”:258,“clouds”:33,“rain”:1.34},{“dt” 1410674400, “温度”:{ “天”:300.01, “分”:298.37, “最大”:300.01, “夜”:298.48, “EVE”:298.37, “早晨”:298.87}, “压力”:1010.17, “湿度”:0,“天气”:[{“id”:501,“main”:“雨”,“描述”:“温和 雨”,“图标”:“10d”}],“速度”: 8.36, “度”:253, “云”:55, “雨”:8.91}

,然后你得到标记物 “鳕鱼”

contacts = jsonObj.getJSONArray(TAG_COd) 

“鳕鱼”: “200”

你会得到“200”

如何将“200”转换为JSONArray? 阵列结构仅是这样 [{ “DT”:1409896800},{ “DT”:1409896800},{ “DT”:1409896800},{ “DT”:1409896800}]

开始于“[ “并以”]结尾“

+0

谢谢我明白你的观点。现在我编辑了代码。 (请看看)这是给arrayOutofRange异常。因为我认为阵列天气有4个元素。但它说[0-1]是范围。 – Isuru 2014-09-05 06:06:24

相关问题