Получение этой ошибки при анализе данных в формате JSON в Android

#java #android #json

#java #Android #json

Вопрос:

Я получаю эту ошибку:

org.json.JSONException: значение http типа java.lang.Строка не может быть преобразована в JSONObject

 public class QueryUtils {

    private QueryUtils(){

    }

    //private static final String URL = "http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojsonamp;starttime=2016-01-01amp;endtime=2016-01-31amp;minmag=6amp;limit=10";

    public static ArrayList<Earthquake> extractEarthquakes() {

         String URL = "http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojsonamp;starttime=2016-01-01amp;endtime=2016-01-31amp;minmag=6amp;limit=10";

        ArrayList<Earthquake> earthquakes = new ArrayList<Earthquake>();

        try {

            String responseDate = URL.toString();
            JSONObject rootObject = new JSONObject(responseDate);
            JSONArray features = rootObject.getJSONArray("features");

//           Date dateObject;
//            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM DD,yyyy h:mm a", Locale.ENGLISH);

            //iterate through loop to display each value

            for(int i=0; i <features.length(); i  ){
                JSONObject jsonObjectForDetails = features.getJSONObject(i);

                JSONObject jsonObjectForProperties = jsonObjectForDetails.getJSONObject("properties");

//                double magValue = double.parseInt(jsonObjectForProperties.optString("mag").toString());
//                String addressDetails = jsonObjectForProperties.optString("place").toString();
//                int dateDetails = Integer.parseInt(jsonObjectForProperties.optString("time").toString());

                double magValue = jsonObjectForProperties.getDouble("mag");
                String addressDetails = jsonObjectForProperties.getString("place");
                long  dateDetails = jsonObjectForProperties.getLong("time");

               // dateObject = new Date(dateDetails);
               // long  dateToDisplay = simpleDateFormat.format(dateObject);
                earthquakes.add(new Earthquake(magValue,addressDetails,dateDetails));

            }

        } catch (JSONException e) {
            Log.e("QueryUtils", "Problem parsing the earthquake JSON results", e);
        }

        return earthquakes;
    }

}
  

Комментарии:

1. где происходит сбой? а именно строка, пожалуйста http://jsonlint.com/ , говорит, что это нормально.

2. String responseDate = URL.toString(); как вы думаете, что это делает?

3. 1) вы никогда не получаете данные json из URL-адреса 2) вы, вероятно, получите исключение NetworkOnMainThread, если вы не вызвали это в AsyncTask

4. Используйте okhttp , чтобы получить ответ, а затем попытаться проанализировать его.

5. Это правильно, я использую retrofit для получения ответа, а затем я его проанализирую. Спасибо за вашу помощь.

Ответ №1:

подводя итог другим комментариям:

для извлечения данных из URL используйте эту функцию:

 public static String getJsonFromServer(String url) throws IOException {

    BufferedReader inputStream = null;

    URL jsonUrl = new URL(url);
    URLConnection dc = jsonUrl.openConnection();

    dc.setConnectTimeout(5000);
    dc.setReadTimeout(5000);

    inputStream = new BufferedReader(new InputStreamReader(
            dc.getInputStream()));

    // read the JSON results into a string
    String jsonResult = inputStream.readLine();
    return jsonResu<
}
  

для вашего случая используйте

  try {
            String responseDate= getJsonFromServer(URL);
//the other code:
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
  

вместо String responseDate = URL.toString();

и этот код (для синтаксического анализа json) тоже работает:

 import org.json.JSONArray;
import org.json.JSONObject;


    public class EarthQuakeTest {
        //http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojsonamp;starttime=2016-01-01amp;endtime=2016-01-31amp;minmag=6amp;limit=10
        private static final String str = "{"type":"FeatureCollection","metadata":{"generated":1475336259000,"url":"http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojsonamp;starttime=2016-01-01amp;endtime=2016-01-31amp;minmag=6amp;limit=10","title":"USGS Earthquakes","status":200,"api":"1.5.2","limit":10,"offset":1,"count":10},"features":[{"type":"Feature","properties":{"mag":7.2,"place":"88km N of Yelizovo, Russia","time":1454124312220,"updated":1463685050282,"tz":720,"url":"http://earthquake.usgs.gov/earthquakes/eventpage/us20004vvx","detail":"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us20004vvxamp;format=geojson","felt":2,"cdi":3.4,"mmi":5.82,"alert":"green","status":"reviewed","tsunami":1,"sig":798,"net":"us","code":"20004vvx","ids":",gcmt20160130032510,at00o1qxho,pt16030050,us20004vvx,gcmt20160130032512,","sources":",gcmt,at,pt,us,gcmt,","types":",associate,cap,dyfi,finite-fault,general-link,general-text,geoserve,impact-link,impact-text,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,","nst":null,"dmin":0.958,"rms":1.19,"gap":17,"magType":"mww","type":"earthquake","title":"M 7.2 - 88km N of Yelizovo, Russia"},"geometry":{"type":"Point","coordinates":[158.5463,53.9776,177]},"id":"us20004vvx"},rn{"type":"Feature","properties":{"mag":6.1,"place":"94km SSE of Taron, Papua New Guinea","time":1453777820750,"updated":1466450055338,"tz":600,"url":"http://earthquake.usgs.gov/earthquakes/eventpage/us20004uks","detail":"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us20004uksamp;format=geojson","felt":null,"cdi":null,"mmi":4.1,"alert":"green","status":"reviewed","tsunami":1,"sig":572,"net":"us","code":"20004uks","ids":",gcmt20160126031023,us20004uks,gcmt20160126031020,","sources":",gcmt,us,gcmt,","types":",associate,cap,geoserve,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,","nst":null,"dmin":1.537,"rms":0.74,"gap":25,"magType":"mww","type":"earthquake","title":"M 6.1 - 94km SSE of Taron, Papua New Guinea"},"geometry":{"type":"Point","coordinates":[153.2454,-5.2952,26]},"id":"us20004uks"},rn{"type":"Feature","properties":{"mag":6.3,"place":"50km NNE of Al Hoceima, Morocco","time":1453695722730,"updated":1466450270946,"tz":0,"url":"http://earthquake.usgs.gov/earthquakes/eventpage/us10004gy9","detail":"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us10004gy9amp;format=geojson","felt":117,"cdi":7.2,"mmi":5.28,"alert":"green","status":"reviewed","tsunami":0,"sig":695,"net":"us","code":"10004gy9","ids":",gcmt20160125042203,us10004gy9,gcmt20160125042202,","sources":",gcmt,us,gcmt,","types":",associate,cap,dyfi,geoserve,impact-text,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,","nst":null,"dmin":2.201,"rms":0.92,"gap":20,"magType":"mww","type":"earthquake","title":"M 6.3 - 50km NNE of Al Hoceima, Morocco"},"geometry":{"type":"Point","coordinates":[-3.6818,35.6493,12]},"id":"us10004gy9"},rn{"type":"Feature","properties":{"mag":7.1,"place":"86km E of Old Iliamna, Alaska","time":1453631430230,"updated":1469293028539,"tz":-540,"url":"http://earthquake.usgs.gov/earthquakes/eventpage/us10004gqp","detail":"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us10004gqpamp;format=geojson","felt":1816,"cdi":7.2,"mmi":6.6,"alert":"green","status":"reviewed","tsunami":1,"sig":1496,"net":"us","code":"10004gqp","ids":",at00o1gd6r,us10004gqp,ak12496371,gcmt20160124103030,","sources":",at,us,ak,gcmt,","types":",cap,dyfi,finite-fault,general-link,general-text,geoserve,impact-link,impact-text,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,trump-origin,","nst":null,"dmin":0.72,"rms":2.11,"gap":19,"magType":"mww","type":"earthquake","title":"M 7.1 - 86km E of Old Iliamna, Alaska"},"geometry":{"type":"Point","coordinates":[-153.4051,59.6363,129]},"id":"us10004gqp"},rn{"type":"Feature","properties":{"mag":6.6,"place":"215km SW of Tomatlan, Mexico","time":1453399617650,"updated":1466450324948,"tz":-420,"url":"http://earthquake.usgs.gov/earthquakes/eventpage/us10004g4l","detail":"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us10004g4lamp;format=geojson","felt":11,"cdi":2.7,"mmi":3.92,"alert":"green","status":"reviewed","tsunami":1,"sig":673,"net":"us","code":"10004g4l","ids":",gcmt20160121180659,at00o1bebo,pt16021050,us10004g4l,gcmt20160121180657,","sources":",gcmt,at,pt,us,gcmt,","types":",associate,cap,dyfi,geoserve,impact-link,impact-text,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,","nst":null,"dmin":2.413,"rms":0.98,"gap":74,"magType":"mww","type":"earthquake","title":"M 6.6 - 215km SW of Tomatlan, Mexico"},"geometry":{"type":"Point","coordinates":[-106.9337,18.8239,10]},"id":"us10004g4l"},rn{"type":"Feature","properties":{"mag":6.7,"place":"52km SE of Shizunai, Japan","time":1452741933640,"updated":1466450357311,"tz":540,"url":"http://earthquake.usgs.gov/earthquakes/eventpage/us10004ebx","detail":"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us10004ebxamp;format=geojson","felt":51,"cdi":5.8,"mmi":6.45,"alert":"green","status":"reviewed","tsunami":1,"sig":720,"net":"us","code":"10004ebx","ids":",us10004ebx,gcmt20160114032534,pt16014050,at00o0xauk,gcmt20160114032533,","sources":",us,gcmt,pt,at,gcmt,","types":",associate,cap,dyfi,geoserve,impact-link,impact-text,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,","nst":null,"dmin":0.281,"rms":0.98,"gap":22,"magType":"mww","type":"earthquake","title":"M 6.7 - 52km SE of Shizunai, Japan"},"geometry":{"type":"Point","coordinates":[142.781,41.9723,46]},"id":"us10004ebx"},rn{"type":"Feature","properties":{"mag":6.1,"place":"12km WNW of Charagua, Bolivia","time":1452741928270,"updated":1463165886000,"tz":-240,"url":"http://earthquake.usgs.gov/earthquakes/eventpage/us10004ebw","detail":"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us10004ebwamp;format=geojson","felt":3,"cdi":2.2,"mmi":2.21,"alert":"green","status":"reviewed","tsunami":0,"sig":573,"net":"us","code":"10004ebw","ids":",us10004ebw,gcmt20160114032528,","sources":",us,gcmt,","types":",cap,dyfi,geoserve,impact-text,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,","nst":null,"dmin":5.492,"rms":1.04,"gap":16,"magType":"mww","type":"earthquake","title":"M 6.1 - 12km WNW of Charagua, Bolivia"},"geometry":{"type":"Point","coordinates":[-63.3288,-19.7597,582.56]},"id":"us10004ebw"},rn{"type":"Feature","properties":{"mag":6.2,"place":"74km NW of Rumoi, Japan","time":1452532083920,"updated":1463165873000,"tz":540,"url":"http://earthquake.usgs.gov/earthquakes/eventpage/us10004djn","detail":"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us10004djnamp;format=geojson","felt":8,"cdi":3.4,"mmi":3.74,"alert":"green","status":"reviewed","tsunami":0,"sig":594,"net":"us","code":"10004djn","ids":",us10004djn,gcmt20160111170803,","sources":",us,gcmt,","types":",cap,dyfi,geoserve,impact-text,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,","nst":null,"dmin":1.139,"rms":0.96,"gap":33,"magType":"mww","type":"earthquake","title":"M 6.2 - 74km NW of Rumoi, Japan"},"geometry":{"type":"Point","coordinates":[141.0867,44.4761,238.81]},"id":"us10004djn"},rn{"type":"Feature","properties":{"mag":6.5,"place":"227km SE of Sarangani, Philippines","time":1452530285900,"updated":1466450384901,"tz":480,"url":"http://earthquake.usgs.gov/earthquakes/eventpage/us10004dj5","detail":"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us10004dj5amp;format=geojson","felt":1,"cdi":2.7,"mmi":7.5,"alert":"green","status":"reviewed","tsunami":1,"sig":650,"net":"us","code":"10004dj5","ids":",gcmt20160111163807,at00o0srjp,pt16011050,us10004dj5,gcmt20160111163805,","sources":",gcmt,at,pt,us,gcmt,","types":",associate,cap,dyfi,geoserve,impact-link,impact-text,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,","nst":null,"dmin":3.144,"rms":0.72,"gap":22,"magType":"mww","type":"earthquake","title":"M 6.5 - 227km SE of Sarangani, Philippines"},"geometry":{"type":"Point","coordinates":[126.8621,3.8965,13]},"id":"us10004dj5"},rn{"type":"Feature","properties":{"mag":6,"place":"Pacific-Antarctic Ridge","time":1451986454620,"updated":1466450408406,"tz":-540,"url":"http://earthquake.usgs.gov/earthquakes/eventpage/us10004bgk","detail":"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us10004bgkamp;format=geojson","felt":0,"cdi":1,"mmi":0,"alert":"green","status":"reviewed","tsunami":0,"sig":554,"net":"us","code":"10004bgk","ids":",gcmt20160105093415,us10004bgk,gcmt20160105093414,","sources":",gcmt,us,gcmt,","types":",associate,cap,dyfi,geoserve,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,","nst":null,"dmin":30.75,"rms":0.67,"gap":71,"magType":"mww","type":"earthquake","title":"M 6.0 - Pacific-Antarctic Ridge"},"geometry":{"type":"Point","coordinates":[-136.2603,-54.2906,10]},"id":"us10004bgk"}],"bbox":[-153.4051,-54.2906,10,158.5463,59.6363,582.56]}";
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            JSONObject rootObject = new JSONObject(str);
            JSONArray features = rootObject.getJSONArray("features");

             for(int i=0; i <features.length(); i  ){
                 JSONObject jsonObjectForDetails = features.getJSONObject(i);

                 JSONObject jsonObjectForProperties = jsonObjectForDetails.getJSONObject("properties");


                 double magValue = jsonObjectForProperties.getDouble("mag");
                 String addressDetails = jsonObjectForProperties.getString("place");
                 long  dateDetails = jsonObjectForProperties.getLong("time");

                // dateObject = new Date(dateDetails);
                // long  dateToDisplay = simpleDateFormat.format(dateObject);
                // earthquakes.add(new Earthquake(magValue,addressDetails,dateDetails));

                 System.out.println(magValue   " "   addressDetails   " "   dateDetails);
             }
            System.out.println(rootObject.hashCode());
        }

    }
  

Комментарии:

1. На самом деле это не решает проблему… JSON никогда не загружается с URL-адреса

2. @cricket_007, я удалю 🙂