【问题标题】:Retrofit 2 (in Android) after implementation, Where are my JSON elements?实施后改造 2(在 Android 中),我的 JSON 元素在哪里?
【发布时间】:2016-06-27 23:46:19
【问题描述】:

我正在实现一个改造 2 接口来解析 JSON 元素(视频网址、缩略图、标题等)

JSONschema2Pojo 产生了 4 个 pojo 类,但主要/根类是 VideoInfo(没关系实现 Parcelable,我还没有用它做任何事情) 知道这是由 jsonschema2pojo 自动生成的,缺少 @SerializedName("....") 是否会影响任何事情?更新:生成了新的 pojo 类,这次使用 Gson 注释 (@SerializedName("") and @Expose) 但仍然存在同样的问题。

import android.os.Parcel;
import android.os.Parcelable;

import java.util.ArrayList;
import java.util.List;

public class VideoInfo implements Parcelable {

    private List<Item> items = new ArrayList<Item>();
    private int pageNumber;
    private int pageSize;
    private int totalCount;

    /**
     * No args constructor for use in serialization
     * 
     */
    public VideoInfo() {
    }

    /**
     * 
     * @param totalCount
     * @param items
     * @param pageSize
     * @param pageNumber
     */
    public VideoInfo(List<Item> items, int pageNumber, int pageSize, int totalCount) {
        this.items = items;
        this.pageNumber = pageNumber;
        this.pageSize = pageSize;
        this.totalCount = totalCount;
    }

    /**
     * 
     * @return
     *     The items
     */
    public List<Item> getItems() {
        return items;
    }

    /**
     * 
     * @param items
     *     The items
     */
    public void setItems(List<Item> items) {
        this.items = items;
    }

    /**
     * 
     * @return
     *     The pageNumber
     */
    public int getPageNumber() {
        return pageNumber;
    }

    /**
     * 
     * @param pageNumber
     *     The page_number
     */
    public void setPageNumber(int pageNumber) {
        this.pageNumber = pageNumber;
    }

    /**
     * 
     * @return
     *     The pageSize
     */
    public int getPageSize() {
        return pageSize;
    }

    /**
     * 
     * @param pageSize
     *     The page_size
     */
    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    /**
     * 
     * @return
     *     The totalCount
     */
    public int getTotalCount() {
        return totalCount;
    }

    /**
     * 
     * @param totalCount
     *     The total_count
     */
    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {

    }


}

更新:在上面的VideoInfo类中你可以看到private List&lt;Item&gt; items = new ArrayList&lt;Item&gt;();这是因为还有一个pojo类有一个tiems列表,如下:

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import java.util.ArrayList;
import java.util.List;

public class Item {

    @SerializedName("id")
    @Expose
    private int id;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("shortDescription")
    @Expose
    private String shortDescription;
    @SerializedName("creationDate")
    @Expose
    private String creationDate;
    @SerializedName("publishedDate")
    @Expose
    private String publishedDate;
    @SerializedName("linkURL")
    @Expose
    private String linkURL;
    @SerializedName("linkText")
    @Expose
    private String linkText;
    @SerializedName("tags")
    @Expose
    private List<String> tags = new ArrayList<String>();
    @SerializedName("videoStillURL")
    @Expose
    private String videoStillURL;
    @SerializedName("thumbnailURL")
    @Expose
    private String thumbnailURL;
    @SerializedName("length")
    @Expose
    private int length;
    @SerializedName("renditions")
    @Expose
    private List<Rendition> renditions = new ArrayList<Rendition>();
    @SerializedName("IOSRenditions")
    @Expose
    private List<IOSRendition> IOSRenditions = new ArrayList<IOSRendition>();
    @SerializedName("HDSRenditions")
    @Expose
    private List<Object> HDSRenditions = new ArrayList<Object>();

    /**
     * No args constructor for use in serialization
     * 
     */
    public Item() {
    }

    /**
     * 
     * @param tags
     * @param videoStillURL
     * @param HDSRenditions
     * @param id
     * @param creationDate
     * @param IOSRenditions
     * @param linkText
     * @param shortDescription
     * @param renditions
     * @param name
     * @param linkURL
     * @param length
     * @param publishedDate
     * @param thumbnailURL
     */
    public Item(int id, String name, String shortDescription, String creationDate, String publishedDate, String linkURL, String linkText, List<String> tags, String videoStillURL, String thumbnailURL, int length, List<Rendition> renditions, List<IOSRendition> IOSRenditions, List<Object> HDSRenditions) {
        this.id = id;
        this.name = name;
        this.shortDescription = shortDescription;
        this.creationDate = creationDate;
        this.publishedDate = publishedDate;
        this.linkURL = linkURL;
        this.linkText = linkText;
        this.tags = tags;
        this.videoStillURL = videoStillURL;
        this.thumbnailURL = thumbnailURL;
        this.length = length;
        this.renditions = renditions;
        this.IOSRenditions = IOSRenditions;
        this.HDSRenditions = HDSRenditions;
    }

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

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

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

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

    /**
     * 
     * @return
     *     The shortDescription
     */
    public String getShortDescription() {
        return shortDescription;
    }

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

    /**
     * 
     * @return
     *     The creationDate
     */
    public String getCreationDate() {
        return creationDate;
    }

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

    /**
     * 
     * @return
     *     The publishedDate
     */
    public String getPublishedDate() {
        return publishedDate;
    }

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

    /**
     * 
     * @return
     *     The linkURL
     */
    public String getLinkURL() {
        return linkURL;
    }

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

    /**
     * 
     * @return
     *     The linkText
     */
    public String getLinkText() {
        return linkText;
    }

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

    /**
     * 
     * @return
     *     The tags
     */
    public List<String> getTags() {
        return tags;
    }

    /**
     * 
     * @param tags
     *     The tags
     */
    public void setTags(List<String> tags) {
        this.tags = tags;
    }

    /**
     * 
     * @return
     *     The videoStillURL
     */
    public String getVideoStillURL() {
        return videoStillURL;
    }

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

    /**
     * 
     * @return
     *     The thumbnailURL
     */
    public String getThumbnailURL() {
        return thumbnailURL;
    }

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

    /**
     * 
     * @return
     *     The length
     */
    public int getLength() {
        return length;
    }

    /**
     * 
     * @param length
     *     The length
     */
    public void setLength(int length) {
        this.length = length;
    }

    /**
     * 
     * @return
     *     The renditions
     */
    public List<Rendition> getRenditions() {
        return renditions;
    }

    /**
     * 
     * @param renditions
     *     The renditions
     */
    public void setRenditions(List<Rendition> renditions) {
        this.renditions = renditions;
    }

    /**
     * 
     * @return
     *     The IOSRenditions
     */
    public List<IOSRendition> getIOSRenditions() {
        return IOSRenditions;
    }

    /**
     * 
     * @param IOSRenditions
     *     The IOSRenditions
     */
    public void setIOSRenditions(List<IOSRendition> IOSRenditions) {
        this.IOSRenditions = IOSRenditions;
    }

    /**
     * 
     * @return
     *     The HDSRenditions
     */
    public List<Object> getHDSRenditions() {
        return HDSRenditions;
    }

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

}

更新:所以上面你可以看到我们已经定义了private List&lt;Rendition&gt; renditions = new ArrayList&lt;Rendition&gt;();,它是在另一个 pojo 类 Rendition.class 中定义的:

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Rendition {

    @SerializedName("audioOnly")
    @Expose
    private boolean audioOnly;
    @SerializedName("controllerType")
    @Expose
    private String controllerType;
    @SerializedName("displayName")
    @Expose
    private String displayName;
    @SerializedName("encodingRate")
    @Expose
    private int encodingRate;
    @SerializedName("frameHeight")
    @Expose
    private int frameHeight;
    @SerializedName("frameWidth")
    @Expose
    private int frameWidth;
    @SerializedName("id")
    @Expose
    private int id;
    @SerializedName("referenceId")
    @Expose
    private Object referenceId;
    @SerializedName("remoteStreamName")
    @Expose
    private Object remoteStreamName;
    @SerializedName("remoteUrl")
    @Expose
    private Object remoteUrl;
    @SerializedName("size")
    @Expose
    private int size;
    @SerializedName("uploadTimestampMillis")
    @Expose
    private int uploadTimestampMillis;
    @SerializedName("url")
    @Expose
    private String url;
    @SerializedName("videoCodec")
    @Expose
    private String videoCodec;
    @SerializedName("videoContainer")
    @Expose
    private String videoContainer;
    @SerializedName("videoDuration")
    @Expose
    private int videoDuration;

    /**
     * No args constructor for use in serialization
     * 
     */
    public Rendition() {
    }

    /**
     * 
     * @param controllerType
     * @param encodingRate
     * @param referenceId
     * @param url
     * @param size
     * @param id
     * @param uploadTimestampMillis
     * @param frameWidth
     * @param remoteUrl
     * @param videoContainer
     * @param remoteStreamName
     * @param displayName
     * @param videoCodec
     * @param videoDuration
     * @param audioOnly
     * @param frameHeight
     */
    public Rendition(boolean audioOnly, String controllerType, String displayName, int encodingRate, int frameHeight, int frameWidth, int id, Object referenceId, Object remoteStreamName, Object remoteUrl, int size, int uploadTimestampMillis, String url, String videoCodec, String videoContainer, int videoDuration) {
        this.audioOnly = audioOnly;
        this.controllerType = controllerType;
        this.displayName = displayName;
        this.encodingRate = encodingRate;
        this.frameHeight = frameHeight;
        this.frameWidth = frameWidth;
        this.id = id;
        this.referenceId = referenceId;
        this.remoteStreamName = remoteStreamName;
        this.remoteUrl = remoteUrl;
        this.size = size;
        this.uploadTimestampMillis = uploadTimestampMillis;
        this.url = url;
        this.videoCodec = videoCodec;
        this.videoContainer = videoContainer;
        this.videoDuration = videoDuration;
    }

    /**
     * 
     * @return
     *     The audioOnly
     */
    public boolean isAudioOnly() {
        return audioOnly;
    }

    /**
     * 
     * @param audioOnly
     *     The audioOnly
     */
    public void setAudioOnly(boolean audioOnly) {
        this.audioOnly = audioOnly;
    }

    /**
     * 
     * @return
     *     The controllerType
     */
    public String getControllerType() {
        return controllerType;
    }

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

    /**
     * 
     * @return
     *     The displayName
     */
    public String getDisplayName() {
        return displayName;
    }

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

    /**
     * 
     * @return
     *     The encodingRate
     */
    public int getEncodingRate() {
        return encodingRate;
    }

    /**
     * 
     * @param encodingRate
     *     The encodingRate
     */
    public void setEncodingRate(int encodingRate) {
        this.encodingRate = encodingRate;
    }

    /**
     * 
     * @return
     *     The frameHeight
     */
    public int getFrameHeight() {
        return frameHeight;
    }

    /**
     * 
     * @param frameHeight
     *     The frameHeight
     */
    public void setFrameHeight(int frameHeight) {
        this.frameHeight = frameHeight;
    }

    /**
     * 
     * @return
     *     The frameWidth
     */
    public int getFrameWidth() {
        return frameWidth;
    }

    /**
     * 
     * @param frameWidth
     *     The frameWidth
     */
    public void setFrameWidth(int frameWidth) {
        this.frameWidth = frameWidth;
    }

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

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

    /**
     * 
     * @return
     *     The referenceId
     */
    public Object getReferenceId() {
        return referenceId;
    }

    /**
     * 
     * @param referenceId
     *     The referenceId
     */
    public void setReferenceId(Object referenceId) {
        this.referenceId = referenceId;
    }

    /**
     * 
     * @return
     *     The remoteStreamName
     */
    public Object getRemoteStreamName() {
        return remoteStreamName;
    }

    /**
     * 
     * @param remoteStreamName
     *     The remoteStreamName
     */
    public void setRemoteStreamName(Object remoteStreamName) {
        this.remoteStreamName = remoteStreamName;
    }

    /**
     * 
     * @return
     *     The remoteUrl
     */
    public Object getRemoteUrl() {
        return remoteUrl;
    }

    /**
     * 
     * @param remoteUrl
     *     The remoteUrl
     */
    public void setRemoteUrl(Object remoteUrl) {
        this.remoteUrl = remoteUrl;
    }

    /**
     * 
     * @return
     *     The size
     */
    public int getSize() {
        return size;
    }

    /**
     * 
     * @param size
     *     The size
     */
    public void setSize(int size) {
        this.size = size;
    }

    /**
     * 
     * @return
     *     The uploadTimestampMillis
     */
    public int getUploadTimestampMillis() {
        return uploadTimestampMillis;
    }

    /**
     * 
     * @param uploadTimestampMillis
     *     The uploadTimestampMillis
     */
    public void setUploadTimestampMillis(int uploadTimestampMillis) {
        this.uploadTimestampMillis = uploadTimestampMillis;
    }

    /**
     * 
     * @return
     *     The url
     */
    public String getUrl() {
        return url;
    }

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

    /**
     * 
     * @return
     *     The videoCodec
     */
    public String getVideoCodec() {
        return videoCodec;
    }

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

    /**
     * 
     * @return
     *     The videoContainer
     */
    public String getVideoContainer() {
        return videoContainer;
    }

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

    /**
     * 
     * @return
     *     The videoDuration
     */
    public int getVideoDuration() {
        return videoDuration;
    }

    /**
     * 
     * @param videoDuration
     *     The videoDuration
     */
    public void setVideoDuration(int videoDuration) {
        this.videoDuration = videoDuration;
    }

}

我已经创建了一个改造接口 VideoInterface.class

导入 retrofit2.Call; 导入改造2.http.GET;

/**
* retrofit 2 interface
 */
public interface VideoInterface {
    String apiURL = ".....";

    @GET(apiURL)
    public Call<VideosResponse> listVideos();
}

我创建了一个响应/解析类 VideosResponse.java

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.ArrayList;
import java.util.List;

/**
 */
public class VideosResponse {
//initalizing the collection
        List<VideoInfo> videos;

        public VideosResponse() {
            videos = new ArrayList<VideoInfo>();
        }
//parsing the response
    public static VideosResponse parseJSON(String response) {
        Gson gson = new GsonBuilder().create();
        VideosResponse videosResponse = gson.fromJson(response, VideosResponse.class);

        return videosResponse;
    }
}

已更新:最后我调用了 API,但无法获取单个元素 我知道我应该能够执行诸如 response.body().getItem().getID().getRendition().getUrl() 之类的操作,但我在自动完成中看不到它,如果我写它,我会收到错误。 这段代码在我的onResume()方法中,我之所以在下面注释掉public static是因为它不允许在onResume()中使用

        // Creating a simple REST adapter which points the API

//        public static
        final String BASE_URL = "http://api......";
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        // Creating an instance of our API interface.

        VideoInterface service = retrofit.create(VideoInterface.class);

        Call<VideosResponse> call = service.listVideos();
        call.enqueue(new Callback<VideosResponse>() {
            @Override
            public void onResponse(Call<VideosResponse> call, Response<VideosResponse> response) {
                VideosResponse videoResponse = response.body();

            }

            @Override
            public void onFailure(Call<VideosResponse> call, Throwable t) {

            }});

最后一步似乎一切正常(没有错误),以下日志给了我:

        Log.d("Videos ", response.message()); //OK
        Log.d("Videos ", String.valueOf(response.isSuccess())); //TRUE
        Log.d("Videos ", String.valueOf(response.code())); //200

但我仍然无法获得所需的字符串。当我打印响应日志时,显示响应 VideosResponse videoResponse = response.body(); 我得到: VideosResponse@3b8bfaa4,这正常吗?我怎么能用这个? 是否建议使用 Parcelable?它会改变什么吗?

【问题讨论】:

  • 你没有在任何地方使用这个VideosResponse videoResponse = response.body();
  • 只用于记录,不做任何事情
  • 那么你是如何阅读回复的?
  • 尝试了上面的 videoResponse.getItem() ,一些在 pojo 中定义的 getter,但这并没有让我到任何地方。
  • 当我打印响应日志时显示响应VideosResponse videoResponse = response.body(); 我得到:VideosResponse@3b8bfaa4,这是正常的吗?我该如何使用它?

标签: java android json retrofit retrofit2


【解决方案1】:

您需要向我们展示 json 响应,或者您也可以自己弄清楚。基本上对象属性名称必须与json属性匹配,您可以debug查看元素是否接收到值,如果没有则添加SerializedName 注释。从那里开始,您有两种可能性:一个对象或一个数组。您可以进一步为其创建 POJO 或创建 List 类型的属性。

【讨论】:

    【解决方案2】:

    我知道我应该能够执行诸如 response.body().item.getID() 之类的操作

    嗯,不,不是基于我理解的代码。

    • response 这里似乎是 Response&lt;VideosResponse&gt; response
    • response.body() 因此将是 VideosResponse
    • response.body().item 将失败,因为 VideosResponse 没有 item 字段

    当我打印响应日志时,显示响应 VideosResponse videoResponse = response.body();我得到: VideosResponse@3b8bfaa4,这正常吗?

    是的。这是尚未覆盖toString() 的Java 对象的默认toString() 输出。这表明response.body()VideosResponse

    我创建了一个响应/解析类 VideosResponse.java

    那么你知道VideosResponse 没有任何名为item 的东西。 Gson 不会向您的类添加方法;它仅基于解析一些 JSON 填充这些类的实例。

    如果您希望 VideosResponse 有一个 item 字段,请确保它存在于您的 JSON 中,然后编辑 VideosResponse 以拥有一个 item 字段。

    【讨论】:

    • 感谢您的回答,我更新了问题以粗体,添加了 2 个其他 pojo 类 (Item & Rendition)。并更新了我想要获取 response.body().getItem().getID().getRendition().getUrl() 的 JSON 元素(来自 VideoInfo 对象的项目->来自项目对象列表的 ID -> 项目的 ID 和项目的 URL),因为我的最终目标是获取要播放的视频 URL。不过,我在自动完成中看不到这些方法。我错过了什么?
    • @user3549911: VideosResponse 没有 getItem() 方法。
    • 我应该将getItem() 方法从pojo Item 移动到VideoResponse 吗?对于这个问题,其他 JSON 元素的所有吸气剂?我的想法是在 Retrofit VideoResponse 知道 VideoInfo pojo 知道 Item Objects 列表知道 Rendition 列表,它获取视频的 URL
    【解决方案3】:

    将 toString() 添加到您的 VideoInfo 类,然后 onResponse 您可以使用类似

    的内容记录返回列表的单个对象

    for (VideoInfo videoInfo : videoResponses) Log.d(LOG_TAG, "VideoInfo: " + videoInfo.toString());

    【讨论】:

    • 如果我想返回几个元素,创建 toString() 方法会很棘手,我正在寻找一个更好的实践解决方案,特别是我正在使用 Retrofit ,这是一个很棒的工具。但是感谢您的帮助。
    • @user3549911 如果您从不实现 toString() 则不能简单地从对象打印,因为有一个自动函数为您生成 toString。 alt+insert, control + enter (mac)
    • 对于每个没有覆盖默认 toString() 方法的对象都是如此。但请注意,我使用的是 Retrofit,它负责 API 调用和解析,所以通常我可以通过编写 response.body().getID().getTitle() 之类的东西从 Retrofit 返回的响应对象中获取 JSON 元素。我的问题是写作在我的情况下不起作用。
    • @user3549911 我不太确定我明白你想做什么。
    • 我已经更新了问题,请阅读上面答案的评论。
    猜你喜欢
    • 2015-12-18
    • 2010-12-24
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 2019-02-09
    • 2021-07-19
    • 1970-01-01
    • 2014-02-09
    相关资源
    最近更新 更多