首页 > 解决方案 > 使用 Retrofit 解析 JSON

问题描述

我必须使用 Retrofit 解析以下 JSON 并显示。

https://api.flickr.com/services/rest/?method=flickr.photos.getRecent&api_key=6f102c62f41998d151e5a1b48713cf13&format=json&nojsoncallback=1&extras=url_s

当我尝试运行我的应用程序时,出现以下错误:

预期BEGIN_ARRAYBEGIN_OBJECT在第 1 行第 2 列路径 $

我的代码如下

MainActivity.java

package com.example.siva.gallery;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

ListView listView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    listView = (ListView) findViewById(R.id.listview);

    //calling the method to display the heroes
    getPhoto();
}

private void getPhoto() {
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Api.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create()) //Here we are using the GsonConverterFactory to directly convert json data to object
            .build();

    Api api = retrofit.create(Api.class);

    Call<List<Photo>> call = api.getPhoto("flickr.photos.getRecent","6f102c62f41998d151e5a1b48713cf13","json","1","url_s");

    call.enqueue(new Callback<List<Photo>>() {
        @Override
        public void onResponse(Call<List<Photo>> call, Response<List<Photo>> response) {
            List<Photo> photoList = response.body();

            //Creating an String array for the ListView
            String[] photos = new String[photoList.size()];

            //looping through all the heroes and inserting the names inside the string array
            for (int i = 0; i < photoList.size(); i++) {
                photos[i] = photoList.get(i).getTitle();
            }


            //displaying the string array into listview
            listView.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, photos));

        }

        @Override
        public void onFailure(Call<List<Photo>> call, Throwable t) {
            Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });
}

}

照片.java

package com.example.siva.gallery;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Photo {

@SerializedName("id")
@Expose
private String id;

@SerializedName("title")
@Expose
private String title;

@SerializedName("url_s")
@Expose
private String urlS;

public Photo(String mId, String mTitle, String mUrls ){
    id = mId;
    title = mTitle;
    urlS = mUrls;
}

public String getId() {
    return id;
}

 public String getTitle() {
    return title;
}
public String getUrlS() {
    return urlS;
}

}

API接口

package com.example.siva.gallery;

import java.util.List;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;

public interface Api {
    String BASE_URL = "https://api.flickr.com/";

    @GET("services/rest/")
    Call<List<Photo>> getPhoto(@Query("method")String method, @Query("api_key") String api_key, @Query("format") String format, @Query("nojsoncallback") String nojsoncallback, @Query("extras") String extras);
    }

我找不到问题所在。

标签: androidjsonretrofit2

解决方案


在此处输入图像描述 你缺少一些包装类,像下面这样添加它们

public class PhotosResult {

    @SerializedName("photos")
    private Photos photos;

    @SerializedName("stat")
    private String stat;

    public Photos getPhotos() {
       return photos;
    }

    public void setPhotos(Photos photos) {
       this.photos = photos;
    }

    public String getStat() {
       return stat;
    }

    public void setStat(String stat) {
       this.stat = stat;
    }

}

public class Photos {
    @SerializedName("photo")
    private List<Photo> photo = null;

    public List<Photo> getPhoto() {
       return photo;
    }

    public void setPhoto(List<Photo> photo) {
       this.photo = photo;
    }
}

因此需要改变api返回类型如下

Call<PhotosResult> getPhoto

这是修改后的 onResponse 方法。

@Override
public void onResponse(Call<PhotosResult> call, Response<PhotosResult> response) {
    PhotosResult  result = response.body();
    for (Photo photo: result.getPhotos().getPhoto()) {
        //photo.getTitle();
    }
}

推荐阅读