Я работаю над проектом в android-studio. Но я застрял на этом пункте. Я сделал запрос с Okhttp3, и это возвращает мне объект Response. Я могу получить ответ в виде строки (из файла json).
MainActivity.java
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if(response.isSuccessful()) {
String data = response.body().string();
JsonParser parser = new JsonParser();
try {
JsonObject obj = (JsonObject) parser.parse(data);
String ad = obj.get("features").toString();
Log.d("msg", data);
Log.d("msg", ad);
Log.d("msg", "Works");
} catch (Exception e) {
Log.d("msg", "Error");
}
Ответ
2019-05-22 10:55:12.785 1301-1631/com.example.triptracker D/msg: {"type":"FeatureCollection","query":[4.35822,51.91962],"features":[{"id":"address.2630076086694170","type":"Feature","place_type":["address"],"relevance":1,"properties":{"accuracy":"point"},"text":"Dotterbloemstraat","place_name":"Dotterbloemstraat 12c, 3135 Vlaardingen, Netherlands","center":[4.358192,51.919666],"geometry":{"type":"Point","coordinates":[4.358192,51.919666]},"address":"12c","context":[{"id":"postcode.7757734261857840","text":"3135"},{"id":"place.6763396954136802","wikidata":"Q210007","text":"Vlaardingen"},{"id":"region.8599455180798270","short_code":"NL-ZH","wikidata":"Q694","text":"Zuid-Holland"},{"id":"country.9349515904622050","short_code":"nl","wikidata":"Q55","text":"Netherlands"}]},{"id":"postcode.7757734261857840","type":"Feature","place_type":["postcode"],"relevance":1,"properties":{},"text":"3135","place_name":"3135, Vlaardingen, Zuid-Holland, Netherlands","bbox":[4.340678,51.909008,4.36899,51.925254],"center":[4.35,51.92],"geometry":{"type":"Point","coordinates":[4.35,51.92]},"context":[{"id":"place.6763396954136802","wikidata":"Q210007","text":"Vlaardingen"},{"id":"region.8599455180798270","short_code":"NL-ZH","wikidata":"Q694","text":"Zuid-Holland"},{"id":"country.9349515904622050","short_code":"nl","wikidata":"Q55","text":"Netherlands"}]},{"id":"place.6763396954136802","type":"Feature","place_type":["place"],"relevance":1,"properties":{"wikidata":"Q210007"},"text":"Vlaardingen","place_name":"Vlaardingen, Zuid-Holland, Netherlands","bbox":[4.270188,51.896102,4.369914,51.951478],"center":[4.35,51.91667],"geometry":{"type":"Point","coordinates":[4.35,51.91667]},"context":[{"id":"region.8599455180798270","short_code":"NL-ZH","wikidata":"Q694","text":"Zuid-Holland"},{"id":"country.9349515904622050","short_code":"nl","wikidata":"Q55","text":"Netherlands"}]},{"id":"region.8599455180798270","type":"Feature","place_type":["region"],"relevance":1,"properties":{"short_code":"NL-ZH","wikidata":"Q694"},"text":"Zuid-Holland","place_name":"Zuid-Holland, Netherlands","bbox":[3.7235244,51.64378,5.150749,52.390802],"center":[4.66667,52],"geometry":{"type":"Point","coordinates":[4.66667,52]},"context":[{"id":"country.9349515904622050","short_code":"nl","wikidata":"Q55","text":"Netherlands"}]},{"id":"country.9349515904622050","type":"Feature","place_type":["country"],"relevance":1,"properties":{"short_code":"nl","wikidata":"Q55"},"text":"Netherlands","place_name":"Netherlands","bbox":[3.1862592,50.750667,7.230902,53.665238],"center":[5.55,52.31667],"geometry":{"type":"Point","coordinates":[5.55,52.31667]}}],"attribution":"NOTICE: © 2019 Mapbox and its suppliers. All rights reserved. Use of this data is subject to the Mapbox Terms of Service (https://www.mapbox.com/about/maps/). This response and the information it contains may not be retained. POI(s) provided by Foursquare."}
2019-05-22 10:55:12.786 1301-1631/com.example.triptracker D/msg: [{"id":"address.2630076086694170","type":"Feature","place_type":["address"],"relevance":1,"properties":{"accuracy":"point"},"text":"Dotterbloemstraat","place_name":"Dotterbloemstraat 12c, 3135 Vlaardingen, Netherlands","center":[4.358192,51.919666],"geometry":{"type":"Point","coordinates":[4.358192,51.919666]},"address":"12c","context":[{"id":"postcode.7757734261857840","text":"3135"},{"id":"place.6763396954136802","wikidata":"Q210007","text":"Vlaardingen"},{"id":"region.8599455180798270","short_code":"NL-ZH","wikidata":"Q694","text":"Zuid-Holland"},{"id":"country.9349515904622050","short_code":"nl","wikidata":"Q55","text":"Netherlands"}]},{"id":"postcode.7757734261857840","type":"Feature","place_type":["postcode"],"relevance":1,"properties":{},"text":"3135","place_name":"3135, Vlaardingen, Zuid-Holland, Netherlands","bbox":[4.340678,51.909008,4.36899,51.925254],"center":[4.35,51.92],"geometry":{"type":"Point","coordinates":[4.35,51.92]},"context":[{"id":"place.6763396954136802","wikidata":"Q210007","text":"Vlaardingen"},{"id":"region.8599455180798270","short_code":"NL-ZH","wikidata":"Q694","text":"Zuid-Holland"},{"id":"country.9349515904622050","short_code":"nl","wikidata":"Q55","text":"Netherlands"}]},{"id":"place.6763396954136802","type":"Feature","place_type":["place"],"relevance":1,"properties":{"wikidata":"Q210007"},"text":"Vlaardingen","place_name":"Vlaardingen, Zuid-Holland, Netherlands","bbox":[4.270188,51.896102,4.369914,51.951478],"center":[4.35,51.91667],"geometry":{"type":"Point","coordinates":[4.35,51.91667]},"context":[{"id":"region.8599455180798270","short_code":"NL-ZH","wikidata":"Q694","text":"Zuid-Holland"},{"id":"country.9349515904622050","short_code":"nl","wikidata":"Q55","text":"Netherlands"}]},{"id":"region.8599455180798270","type":"Feature","place_type":["region"],"relevance":1,"properties":{"short_code":"NL-ZH","wikidata":"Q694"},"text":"Zuid-Holland","place_name":"Zuid-Holland, Netherlands","bbox":[3.7235244,51.64378,5.150749,52.390802],"center":[4.66667,52],"geometry":{"type":"Point","coordinates":[4.66667,52]},"context":[{"id":"country.9349515904622050","short_code":"nl","wikidata":"Q55","text":"Netherlands"}]},{"id":"country.9349515904622050","type":"Feature","place_type":["country"],"relevance":1,"properties":{"short_code":"nl","wikidata":"Q55"},"text":"Netherlands","place_name":"Netherlands","bbox":[3.1862592,50.750667,7.230902,53.665238],"center":[5.55,52.31667],"geometry":{"type":"Point","coordinates":[5.55,52.31667]}}]
2019-05-22 10:55:12.786 1301-1631/com.example.triptracker D/msg: Works
Но мне нужно "place_name", которое вложено в "features". Я так много пробовал, но до сих пор не знаю, как получить доступ к "place_name". В JavaScript это намного проще, например, feature[0].place_name. Но в Java это мне неизвестно. Может кто-нибудь, пожалуйста, помогите.
Результат, который я хочу:
"Dotterbloemstraat 12c, 3135 Vlaardingen, Netherlands"
Преобразуйте свой ответ json в свой модальный класс. Я предлагаю вам использовать библиотеку retofit вместо http Square.github.io/ретрофит
1) Вы используете OkHttp без дооснащения. 2) Вы случайным образом угадываете код вместо того, чтобы читать, как правильно разбирать строку json. Либо внедрите Retrofit Square.github.io/ретрофит, либо прочитайте об анализе json tutorialspoint.com/android/android_json_parser.htm.
попробуйте это - Массив JSONArray = obj.getJSONArray («функции»);JSONObject main_detail = array.getJSONObject(0);Строка place_name = main_detail.getString("place_name");
вы должны получить функции как Json Array
JsonArray ad = obj.getAsJsonArray("features");
JsonObject ob = ad.get(0).getAsJsonObject();
String placeName = ob.get("place_name").getAsString()
Это дает мне следующую ошибку: ошибка: метод getAsJsonObject в классе JsonElement не может быть применен к заданным типам; требуется: аргументы не найдены: int причина: списки фактических и формальных аргументов различаются по длине
я редактировал, попробуй новую версию
Можете ли вы показать нам модели, которые вы создали?