在Android上使用Retrofit进行JSON响应

时间:2016-06-02 05:30:24

标签: android json retrofit okhttp3

我可以使用OkHttp3获取JSON响应,我想使用Retrofit来解析响应以从中获取名称和图像。我查看了Retrofit网站和一些教程,但仍然没有明确的过程。

以下是获取JSON响应的OkHttp3代码:

 Request request = new Request.Builder().url(url).build();

    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()) throw new IOException("Unexpected code " + response);

            Headers responseHeaders = response.headers();
            for (int i = 0, size = responseHeaders.size(); i < size; i++) {
                System.out.println(responseHeaders.name(i) + responseHeaders.value(i));
            }
            System.out.println(response.body().string());
            String jData = response.body().string();// I want to parse jData using Retrofit

        }
    });

JSON响应如下所示:

enter image description here

我想获得每位艺术家的名字,身份证和形象,非常感谢任何帮助。

更新

我添加了Pojo类,其中一个是Item类:

public class Item {

@SerializedName("external_urls")
@Expose
private ExternalUrls externalUrls;
@SerializedName("followers")
@Expose
private Followers followers;
@SerializedName("genres")
@Expose
private List<Object> genres = new ArrayList<Object>();
@SerializedName("href")
@Expose
private String href;
@SerializedName("id")
@Expose
private String id;
@SerializedName("images")
@Expose
private List<Object> images = new ArrayList<Object>();
@SerializedName("name")
@Expose
private String name;
@SerializedName("popularity")
@Expose
private Integer popularity;
@SerializedName("type")
@Expose
private String type;
@SerializedName("uri")
@Expose
private String uri;

/**
 *
 * @return
 * The externalUrls
 */
public ExternalUrls getExternalUrls() {
    return externalUrls;
}

/**
 *
 * @param externalUrls
 * The external_urls
 */
public void setExternalUrls(ExternalUrls externalUrls) {
    this.externalUrls = externalUrls;
}

/**
 *
 * @return
 * The followers
 */
public Followers getFollowers() {
    return followers;
}

/**
 *
 * @param followers
 * The followers
 */
public void setFollowers(Followers followers) {
    this.followers = followers;
}

/**
 *
 * @return
 * The genres
 */
public List<Object> getGenres() {
    return genres;
}

/**
 *
 * @param genres
 * The genres
 */
public void setGenres(List<Object> genres) {
    this.genres = genres;
}

/**
 *
 * @return
 * The href
 */
public String getHref() {
    return href;
}

/**
 *
 * @param href
 * The href
 */
public void setHref(String href) {
    this.href = href;
}

/**
 *
 * @return
 * The id
 */
public String getId() {
    return id;
}

/**
 *
 * @param id
 * The id
 */
public void setId(String id) {
    this.id = id;
}

/**
 *
 * @return
 * The images
 */
public List<Object> getImages() {
    return images;
}

/**
 *
 * @param images
 * The images
 */
public void setImages(List<Object> images) {
    this.images = images;
}

/**
 *
 * @return
 * The name
 */
public String getName() {
    return name;
}

/**
 *
 * @param name
 * The name
 */
public void setName(String name) {
    this.name = name;
}

/**
 *
 * @return
 * The popularity
 */
public Integer getPopularity() {
    return popularity;
}

/**
 *
 * @param popularity
 * The popularity
 */
public void setPopularity(Integer popularity) {
    this.popularity = popularity;
}

/**
 *
 * @return
 * The type
 */
public String getType() {
    return type;
}

/**
 *
 * @param type
 * The type
 */
public void setType(String type) {
    this.type = type;
}

/**
 *
 * @return
 * The uri
 */
public String getUri() {
    return uri;
}

/**
 *
 * @param uri
 * The uri
 */
public void setUri(String uri) {
    this.uri = uri;
}

}

这里我如何在我的活动中使用Retrofit:

    private void loadJSON() {
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://api.spotify.com")
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    final Artists_Interface request = retrofit.create(Artists_Interface.class);

    Call<Item> call = request.getArtists();
    call.enqueue(new Callback<Item>() {
        @Override
        public void onResponse(Call<Item> call, Response<Item> response) {
            if(response.isSuccessful()){
                Item artist = response.body();
                System.out.println("THE NAME::::. : " + artist.getName());
            }
            else{
                System.out.println(" :::. NOO RESPONSE .::: " );
            } 
        }

        @Override
        public void onFailure(Call<Item> call, Throwable t) {
            System.out.println("onFAIL::: " + t);
        }
    });

以下是改造界面的样子:

public interface Artists_Interface {

@GET("/v1/search?q=Beyonce&type=artist")
Call<Item> getArtists();

}

我得到artist.getName()等于null。我需要进入JSON主体中“items”内的name,id和images,并将它们传递给listView或recyclerView适配器

4 个答案:

答案 0 :(得分:5)

这是错误的,

Headers responseHeaders = response.headers();
            for (int i = 0, size = responseHeaders.size(); i < size; i++) {
                System.out.println(responseHeaders.name(i) + responseHeaders.value(i));
            }

您正在尝试在标题中找到名称,ID等数据,而信息位于回复正文中。

只需为您的数据模型创建POJO,并从响应对象中将信息检索到模型中。然后,您只需使用getter和setter来访问所需的数据。

<强>更新

您可以使用此网站http://www.jsonschema2pojo.org轻松创建POJO。只需复制并粘贴您的JSON,它就会立即为您生成POJO。

现在有了POJO,您可以手动解析它,也可以使用GSON或Jackson库轻松完成。

更新2

这里的错误很明显,

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1

它清楚地表明解析器期望一个数组,但在实际的JSON中找到了一个对象。

请参阅实际的JSON,它以对象开头,而不是数组,所以为什么在这里使用List,

Call<List<Item>> getArtists();

如果你看一下你的JSON,你可以看到它以一个对象开始,你在其中有另一个带有关键“艺术家”的对象,然后你有一个带有关键“项目”的项目列表。

您也无需手动执行任何操作。 www.jsonschema2pojo.org会为你生成一切,你只需要包含它们。

我不明白你为什么要包含一个List而不是一个对象。

更新3

Getters男人,简单的吸气剂。

假设你有这个,假设

class Data {

    Artists artists;

    Artists getArtists() {
        return artists;
    }

    class Artists {
        List<Item> list;

        List<Item> getItemList(){
            return  list;
        }
    }

    class Item {
        // You have your item class here
    }
}

现在这样做,

Call<Data> getArtists();

并获取物品,

data.getArtists().getItemList();

现在清楚了吗?

答案 1 :(得分:2)

感谢大家,感谢所有答案。我设法通过拼凑起来解决问题,因为Retrofit的文档很差,而且有些答案还不够详细,无法接受。我想从此链接中提取JSON响应中的数据:https://api.spotify.com/v1/search?q=Beyonce&type=artist

<强>步骤1: 创建一个Pojo类以反序列化响应中的项目。反序列化基本上意味着在这个JSON响应中,我们有#34;艺术家&#34;数组和里面&#34; href&#34;字符串和&#34;项目&#34;列表,正如Aritra建议的那样,我们可以使用http://www.jsonschema2pojo.org来生成pojo类,这些类将为我们反序列化这些项目。在一些修改之后我的样子如何:

public class Data implements Serializable{

@SerializedName("artists")
Artists artists;

public Artists getArtists() {
    return artists;
}


public static class Artists {

    @SerializedName("href")
    private String href;

    @SerializedName("items")
    private List<Item> items;


    public String getHref(){
        return href;
    }

    public List<Item> getItems(){
        return items;
    }

}// Artists



public static class Item {
    // You have your item class here
    @SerializedName("external_urls")
    @Expose
    private ExternalUrls externalUrls;
    @SerializedName("followers")
    @Expose
    private Followers followers;
    @SerializedName("genres")
    @Expose
    private List<Object> genres = new ArrayList<Object>();
    @SerializedName("href")
    @Expose
    private String href;
    @SerializedName("id")
    @Expose
    private String id;
    @SerializedName("images")
    @Expose
    private List<Object> images = new ArrayList<Object>();
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("popularity")
    @Expose
    private Integer popularity;
    @SerializedName("type")
    @Expose
    private String type;
    @SerializedName("uri")
    @Expose
    private String uri;


    public Item() {
        name = "";
        id = "";
        images = new ArrayList<>();
    }


    /**
     * @return The externalUrls
     */
    public ExternalUrls getExternalUrls() {
        return externalUrls;
    }

    /**
     * @param externalUrls The external_urls
     */
    public void setExternalUrls(ExternalUrls externalUrls) {
        this.externalUrls = externalUrls;
    }

    /**
     * @return The followers
     */
    public Followers getFollowers() {
        return followers;
    }

    /**
     * @param followers The followers
     */
    public void setFollowers(Followers followers) {
        this.followers = followers;
    }

    /**
     * @return The genres
     */
    public List<Object> getGenres() {
        return genres;
    }

    /**
     * @param genres The genres
     */
    public void setGenres(List<Object> genres) {
        this.genres = genres;
    }

    /**
     * @return The href
     */
    public String getHref() {
        return href;
    }

    /**
     * @param href The href
     */
    public void setHref(String href) {
        this.href = href;
    }

    /**
     * @return The id
     */
    public String getId() {
        return id;
    }

    /**
     * @param id The id
     */
    public void setId(String id) {
        this.id = id;
    }

    /**
     * @return The images
     */
    public List<Object> getImages() {
        return images;
    }

    /**
     * @param images The images
     */
    public void setImages(List<Object> images) {
        this.images = images;
    }

    /**
     * @return The name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name The name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return The popularity
     */
    public Integer getPopularity() {
        return popularity;
    }

    /**
     * @param popularity The popularity
     */
    public void setPopularity(Integer popularity) {
        this.popularity = popularity;
    }

    /**
     * @return The type
     */
    public String getType() {
        return type;
    }

    /**
     * @param type The type
     */
    public void setType(String type) {
        this.type = type;
    }

    /**
     * @return The uri
     */
    public String getUri() {
        return uri;
    }

    /**
     * @param uri The uri
     */
    public void setUri(String uri) {
        this.uri = uri;
    }

}// Item

}

所以,阵列&#34;艺术家&#34;表示为Artists类,其中包含所有序列化以匹配JSON响应的href String和items列表元素。 items列表是Item类的类型,它包含许多序列化元素,如id,name,images等等。所有序列化元素都被序列化为JSON响应。

<强>步骤2: 网址分为两部分,一个基础和一个端点。我们在创建Retrofit2请求时使用基数。我是从onCreate方法调用此请求:

private void loadJSON() {
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://api.spotify.com")
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    final Artists_Interface request = retrofit.create(Artists_Interface.class);

    Call<Data> call = request.getArtists();
    call.enqueue(new Callback<Data>() {
        @Override
        public void onResponse(Call<Data> call, Response<Data> response) {

            if (response.isSuccessful()) {

                System.out.println(" Href ::::. : " + response.body().getArtists().getHref());

                List<Data.Item> items = response.body().getArtists().getItems();
                    for (int i = 0; i < items.size(); i++) {
                        adapter.addArtist(items.get(i));
                    }
            }
            else { System.out.println(" :::. NO RESPONSE .::: "); }

        }// End onResponse

        @Override
        public void onFailure(Call<Data> call, Throwable t) {
            System.out.println("onFAIL::: " + t);
        }
    });

然后,我们在Retrofit2接口类中使用端点:

public interface Artists_Interface {

@GET("/v1/search?q=Beyonce&type=artist")
Call<Data> getArtists();

}

<强>步骤3: 只需将我们从响应中获得的值分配给视图中的元素即可。在第二步中,我将项目列表分配给了我的recyclerView适配器,所以这里我的适配器是这样的:

public class Artists_Adapter extends RecyclerView.Adapter<Artists_Adapter.ViewHolder> {

private ArrayList<Data.Item> artists;

public Artists_Adapter(ArrayList<Data.Item> artists) {
    this.artists = artists;
}

@Override
public Artists_Adapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_artists, viewGroup, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(Artists_Adapter.ViewHolder viewHolder, int i) {

    viewHolder.name.setText(artists.get(i).getName());

}

@Override
public int getItemCount() {
    if(artists == null){
        return 0;
    }
    else {
        return artists.size();
    }
}

public void addArtist(Data.Item item){

    artists.add(item);

}

public class ViewHolder extends RecyclerView.ViewHolder{
    private TextView name ;
    private ImageView imageView;
    public ViewHolder(View view) {
        super(view);

        name = (TextView)view.findViewById(R.id.name);
        imageView = (ImageView) view.findViewById(R.id.image);

    }
}

}

这是我的onCreate()方法的样子:

    private RecyclerView recyclerView;
private ArrayList<Data.Item> data = new ArrayList<>();
private Artists_Adapter adapter;
static Context ctx;

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

    ctx = this;
    url = "https://api.spotify.com/v1/search?q=Beyonce&type=artist";

    loadJSON();
    initViews();


}// onCreate


private void initViews() {
    recyclerView = (RecyclerView) findViewById(R.id.card_recycler_view);
    recyclerView.setHasFixedSize(true);
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(layoutManager);
    adapter = new Artists_Adapter(data);
    recyclerView.setAdapter(adapter);

}

答案 2 :(得分:1)

您可以使用android JSONObject类,如:

JSONObject json = new JSONObject(response.body().string());

创建对象后,您可以使用.get() method提取必需的字段,就像普通的JSON一样。

答案 3 :(得分:0)

here中有简单的演示,请仔细阅读