коллеги!
Имею json файл:
[{"wrapperType":"track","kind":"song","artistId":1017136601,"collectionId":1051991020,"trackId":1051991441,"artistName":"Kiiara","collectionName":"Gold - Single","trackName":"Gold","collectionCensoredName":"Gold - Single","trackCensoredName":"Gold","artistViewUrl":"https:\/\/music.apple.com\/ru\/artist\/kiiara\/1017136601?uo=4","collectionViewUrl":"https:\/\/music.apple.com\/ru\/album\/gold\/1051991020?i=1051991441\u0026uo=4","trackViewUrl":"https:\/\/music.apple.com\/ru\/album\/gold\/1051991020?i=1051991441\u0026uo=4","previewUrl":"https:\/\/audio-ssl.itunes.apple.com\/itunes-assets\/Music6\/v4\/2b\/a5\/c8\/2ba5c86c-ca23-1f96-dd77-7bd9ad960a40\/mzaf_8477152025865893862.plus.aac.p.m4a","artworkUrl30":"https:\/\/is4-ssl.mzstatic.com\/image\/thumb\/Music69\/v4\/37\/38\/0e\/37380e3d-24ef-004a-e129-c033a46ae3c0\/source\/30x30bb.jpg","artworkUrl60":"https:\/\/is4-ssl.mzstatic.com\/image\/thumb\/Music69\/v4\/37\/38\/0e\/37380e3d-24ef-004a-e129-c033a46ae3c0\/source\/60x60bb.jpg","artworkUrl100":"https:\/\/is4-ssl.mzstatic.com\/image\/thumb\/Music69\/v4\/37\/38\/0e\/37380e3d-24ef-004a-e129-c033a46ae3c0\/source\/100x100bb.jpg","collectionPrice":22,"trackPrice":22,"releaseDate":"2015-03-22T07:00:00Z","collectionExplicitness":"notExplicit","trackExplicitness":"notExplicit","discCount":1,"discNumber":1,"trackCount":1,"trackNumber":1,"trackTimeMillis":225882,"country":"RUS","currency":"RUB","primaryGenreName":"\u041f\u043e\u043f","isStreamable":true,"arCurSong_artistName":"Kiiara","arCurSong_trackName":"Gold"},{"artistName":"Meduza","trackName":"Lose Control","arCurSong_artistName":"Meduza","arCurSong_trackName":"Lose Control"},{"wrapperType":"track","kind":"song","artistId":64387566,"collectionId":1482965877,"trackId":1482965898,"artistName":"Katy Perry","collectionName":"Harleys in Hawaii - Single","trackName":"Harleys in Hawaii","collectionCensoredName":"Harleys in Hawaii - Single","trackCensoredName":"Harleys in Hawaii","artistViewUrl":"https:\/\/music.apple.com\/ru\/artist\/katy-perry\/64387566?uo=4","collectionViewUrl":"https:\/\/music.apple.com\/ru\/album\/harleys-in-hawaii\/1482965877?i=1482965898\u0026uo=4","trackViewUrl":"https:\/\/music.apple.com\/ru\/album\/harleys-in-hawaii\/1482965877?i=1482965898\u0026uo=4","previewUrl":"https:\/\/audio-ssl.itunes.apple.com\/itunes-assets\/AudioPreview123\/v4\/80\/0a\/fa\/800afa07-7058-6fed-f8ea-58664561d773\/mzaf_6669635699190731554.plus.aac.p.m4a","artworkUrl30":"https:\/\/is4-ssl.mzstatic.com\/image\/thumb\/Music123\/v4\/53\/a0\/16\/53a016d9-f6d0-a42c-8fb6-967768de9254\/source\/30x30bb.jpg","artworkUrl60":"https:\/\/is4-ssl.mzstatic.com\/image\/thumb\/Music123\/v4\/53\/a0\/16\/53a016d9-f6d0-a42c-8fb6-967768de9254\/source\/60x60bb.jpg","artworkUrl100":"https:\/\/is4-ssl.mzstatic.com\/image\/thumb\/Music123\/v4\/53\/a0\/16\/53a016d9-f6d0-a42c-8fb6-967768de9254\/source\/100x100bb.jpg","collectionPrice":22,"trackPrice":22,"releaseDate":"2019-10-16T07:00:00Z","collectionExplicitness":"notExplicit","trackExplicitness":"notExplicit","discCount":1,"discNumber":1,"trackCount":1,"trackNumber":1,"trackTimeMillis":185815,"country":"RUS","currency":"RUB","primaryGenreName":"\u041f\u043e\u043f","isStreamable":true,"arCurSong_artistName":"Katy Perry","arCurSong_trackName":"Harleys In Hawaii"}]
Код для его обработки использую:
public class MainActivity extends AppCompatActivity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.music);
getResponse();
}
private void getResponse(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiInterface.JSONURL)
.addConverterFactory(ScalarsConverterFactory.create())
.build();
ApiInterface api = retrofit.create(ApiInterface.class);
Call<String> call = api.getString();
call.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
Log.i("Responsestring", response.body().toString());
if (response.isSuccessful()) {
if (response.body() !=null) {
Log.i("onSuccess", response.body().toString());
String jsonresponse = response.body().toString();
writeMusic (jsonresponse);
} else {
Log.i("OnEmptyResponse", "Returned empty response");
}
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
}
});
}
private void writeMusic (String response) {
try {
JSONObject obj = new JSONObject(response);
ArrayList<MusicModel> musicModelArrayList = new ArrayList<>();
JSONArray dataArray = obj.getJSONArray(response);
for (int i = 0; i<dataArray.length(); i++) {
MusicModel musicModel = new MusicModel();
JSONObject dataobj = dataArray.getJSONObject(i);
musicModel.setArtistName(dataobj.getString("artistName"));
musicModel.setTrackName(dataobj.getString("trackName"));
musicModelArrayList.add(musicModel);
}
for (int j = 0; j < musicModelArrayList.size();j++){
textView.setText(textView.getText()+musicModelArrayList.get(j).getArtistName()+ " " +musicModelArrayList.get(j).getTrackName());
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}
Возможно, мыслю в правильном направлении - указал в строке в скобках значение "response": JSONArray dataArray = obj.getJSONArray(response);
Верно ли это?
Мысль условно-верная, но направление не удобное. Так как в итоге вы хотите получить список объектов модели, то проще будет использовать GsonConverter
.
Добавить зависимость в build.gradle(module):
// номер версии меняем на нужный/актуальный по необходимости
implementation 'com.squareup.retrofit2:converter-gson:2.6.2'
Тип запроса меняем на List<MusicModel>
, для примера:
@Get("api/path")
public Call<List<MusicModel>> getMusic();
Запрос:
private void getResponse() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiInterface.JSONURL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface api = retrofit.create(ApiInterface.class);
Call<List<MusicModel>> call = api.getMusic();
call.enqueue(new Callback<List<MusicModel>>() {
@Override
public void onResponse(Call<List<MusicModel>> call, Response<List<MusicModel>> response) {
if (response.isSuccessful()) {
List<MusicModel> musicModelArrayList = response.body();
if (musicModelArrayList != null) {
showMusicList(musicModelArrayList);
} else {
Log.w("onResponse", "Returned empty response");
}
} else {
Log.w("onResponse", "Not success response: " + response.message());
}
}
@Override
public void onFailure(Call<List<MusicModel>> call, Throwable t) {
Log.e("Retrofit", "onFailure: ", t);
}
});
}
private void showMusicList(List<MusicModel> musicModelArrayList) {
textView.setText(TextUtils.join("\n", musicModelArrayList));
}
Модель (по желанию можно добавить поля, геттеры и сеттеры для других значений):
public class MusicModel {
@SerializedName("artistName")
@Expose
private String artistName;
@SerializedName("trackName")
@Expose
private String trackName;
public String getArtistName() {
return artistName;
}
public void setArtistName(String artistName) {
this.artistName = artistName;
}
public String getTrackName() {
return trackName;
}
public void setTrackName(String trackName) {
this.trackName = trackName;
}
@Override
public String toString() {
return artistName + " - " + trackName;
}
}
Айфон мало держит заряд, разбираемся с проблемой вместе с AppLab
По нажатию на кнопку квадрат изменяет позициюКак сделать это перемещение плавным? Может как то с помощью requestAnimationFrame() или setInterval()? Сам код:
Задано 4 байтовое число, с 10 по 4 биты сдвинуть влево на 3 разряда
В коде что ниже есть такое копирование:
Такой вопрос, (я только учусь, так что не бейте) есть функция, которая удаляет элемент из массива: