如何使用改造 2 在 Android 中获取 Json,如下面的代码所示?

Posted

技术标签:

【中文标题】如何使用改造 2 在 Android 中获取 Json,如下面的代码所示?【英文标题】:How to fetch Json in Android using retrofit 2 as shown in below code? 【发布时间】:2019-03-26 05:27:12 【问题描述】:

api 网址:“http://btownmedia.com/?json=get_category_posts&slug=flex-print&status=publish”

我的json如下所示:

  
"status": "ok",
"count": 1,
"pages": 1,
"category": 
    "id": 44,
    "slug": "flex-print",
    "title": "Flex Print",
    "description": "Flex Print",
    "parent": 7,
    "post_count": 1
,
"posts": [
    
        "id": 343,
        "type": "post",
        "slug": "nk-advertising",
        "url": "https://btownmedia.com/2018/10/10/nk-advertising/",
        "status": "publish",
        "title": "NK Advertising",
        "title_plain": "NK Advertising",
        "content": "<p style=\"color: #7a6666; font-family: roboto-regular-webfont; font-size: 14px; line-height: 24px; margin: 0px; padding: 0px 0px 19px; width: 370px;\"><strong>Online advertisement:</strong> <em>Online advertisement on our website</em> means our basic service. Your business card or a visiting card sized advertisement is displayed on our website for pre-mentioned time frame.</p>\n<p style=\"color: #7a6666; font-family: roboto-regular-webfont; font-size: 14px; line-height: 24px; margin: 0px; padding: 0px 0px 19px; width: 370px;\"><strong>Personalized page:</strong> We offer you a personalized page, designed for your business with all the details of your business- linked with your advertisement that opens when clicked.</p>\n",
        "excerpt": "<p>Online advertisement on our website means our basic service. Your business card or a visiting card sized advertisement is displayed on our website for pre-mentioned time frame.</p>\n",
        "date": "2018-10-10 08:08:29",
        "modified": "2018-10-10 08:08:29",
        "categories": [
            
                "id": 44,
                "slug": "flex-print",
                "title": "Flex Print",
                "description": "Flex Print",
                "parent": 7,
                "post_count": 1
            
        ],
        "tags": [],
        "author": 
            "id": 1,
            "slug": "admin",
            "name": "admin",
            "first_name": "",
            "last_name": "",
            "nickname": "admin",
            "url": "",
            "description": ""
        ,
        "comments": [],
        "attachments": [
            
                "id": 342,
                "url": "https://btownmedia.com/nk/",
                "slug": "nk",
                "title": "nk",
                "description": "",
                "caption": "",
                "parent": 343,
                "mime_type": "image/png",
                "images": 
                    "full": 
                        "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
                        "width": 230,
                        "height": 142
                    ,
                    "thumbnail": 
                        "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk-150x142.png",
                        "width": 150,
                        "height": 142
                    ,
                    "medium": 
                        "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
                        "width": 230,
                        "height": 142
                    ,
                    "medium_large": 
                        "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
                        "width": 230,
                        "height": 142
                    ,
                    "large": 
                        "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
                        "width": 230,
                        "height": 142
                    ,
                    "rpggallery_admin_thumb": 
                        "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
                        "width": 230,
                        "height": 142
                    ,
                    "rpggallery_admin_large": 
                        "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
                        "width": 230,
                        "height": 142
                    ,
                    "rpg_gallery_admin_thumb": 
                        "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk-150x142.png",
                        "width": 150,
                        "height": 142
                    ,
                    "rpg_gallery_thumb": 
                        "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk-150x142.png",
                        "width": 150,
                        "height": 142
                    ,
                    "estore-featured-image": 
                        "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
                        "width": 230,
                        "height": 142
                    ,
                    "estore-product-grid": 
                        "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk-75x75.png",
                        "width": 75,
                        "height": 75
                    ,
                    "estore-square": 
                        "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
                        "width": 230,
                        "height": 142
                    ,
                    "estore-slider": 
                        "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
                        "width": 230,
                        "height": 142
                    ,
                    "estore-medium-image": 
                        "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
                        "width": 230,
                        "height": 142
                    
                
            
        ],
        "comment_count": 0,
        "comment_status": "open",
        "thumbnail": "https://btownmedia.com/wp-content/uploads/2018/10/nk-150x142.png",
        "custom_fields": ,
        "thumbnail_size": "thumbnail",
        "thumbnail_images": 
            "full": 
                "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
                "width": 230,
                "height": 142
            ,
            "thumbnail": 
                "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk-150x142.png",
                "width": 150,
                "height": 142
            ,
            "medium": 
                "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
                "width": 230,
                "height": 142
            ,
            "medium_large": 
                "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
                "width": 230,
                "height": 142
            ,
            "large": 
                "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
                "width": 230,
                "height": 142
            ,
            "rpggallery_admin_thumb": 
                "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
                "width": 230,
                "height": 142
            ,
            "rpggallery_admin_large": 
                "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
                "width": 230,
                "height": 142
            ,
            "rpg_gallery_admin_thumb": 
                "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk-150x142.png",
                "width": 150,
                "height": 142
            ,
            "rpg_gallery_thumb": 
                "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk-150x142.png",
                "width": 150,
                "height": 142
            ,
            "estore-featured-image": 
                "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
                "width": 230,
                "height": 142
            ,
            "estore-product-grid": 
                "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk-75x75.png",
                "width": 75,
                "height": 75
            ,
            "estore-square": 
                "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
                "width": 230,
                "height": 142
            ,
            "estore-slider": 
                "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
                "width": 230,
                "height": 142
            ,
            "estore-medium-image": 
                "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
                "width": 230,
                "height": 142
            
        
    
] 

Pojo 类:

公开课帖子

private Integer id;
private String type;
private String slug;
private String url;
private String status;
private String title;
private String titlePlain;
private String content;
private String excerpt;
private String date;
private String modified;
private List<Object> tags = null;
private List<Object> comments = null;
private Integer commentCount;
private String commentStatus;
private String thumbnail;
private String thumbnailSize;

public Integer getId() 
    return id;


public void setId(Integer id) 
    this.id = id;


public String getType() 
    return type;


public void setType(String type) 
    this.type = type;


public String getSlug() 
    return slug;


public void setSlug(String slug) 
    this.slug = slug;


public String getUrl() 
    return url;


public void setUrl(String url) 
    this.url = url;


public String getStatus() 
    return status;


public void setStatus(String status) 
    this.status = status;


public String getTitle() 
    return title;


public void setTitle(String title) 
    this.title = title;


public String getTitlePlain() 
    return titlePlain;


public void setTitlePlain(String titlePlain) 
    this.titlePlain = titlePlain;


public String getContent() 
    return content;


public void setContent(String content) 
    this.content = content;


public String getExcerpt() 
    return excerpt;


public void setExcerpt(String excerpt) 
    this.excerpt = excerpt;


public String getDate() 
    return date;


public void setDate(String date) 
    this.date = date;


public String getModified() 
    return modified;


public void setModified(String modified) 
    this.modified = modified;




public List<Object> getTags() 
    return tags;


public void setTags(List<Object> tags) 
    this.tags = tags;




public List<Object> getComments() 
    return comments;


public void setComments(List<Object> comments) 
    this.comments = comments;




public Integer getCommentCount() 
    return commentCount;


public void setCommentCount(Integer commentCount) 
    this.commentCount = commentCount;


public String getCommentStatus() 
    return commentStatus;


public void setCommentStatus(String commentStatus) 
    this.commentStatus = commentStatus;


public String getThumbnail() 
    return thumbnail;


public void setThumbnail(String thumbnail) 
    this.thumbnail = thumbnail;




public String getThumbnailSize() 
    return thumbnailSize;


public void setThumbnailSize(String thumbnailSize) 
    this.thumbnailSize = thumbnailSize;

接口API

@GET("json=get_category_posts&slug=flex-print&status=publish")
Call<Post> getListPost();

MainActivity.java

void getListPosts() 

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(url1)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    RetrofitArrayAPI service = retrofit.create(RetrofitArrayAPI.class);
    Log.d("service", String.valueOf(""));

    Call<Post> call = service.getListPost();

    call.enqueue(new Callback<Post>() 
        @Override
        public void onResponse(Response<Post> response, Retrofit retrofit) 

            try 

                Log.d("Title", String.valueOf(response.body()));


             catch (Exception e) 
                Log.d("onResponse", "There is an error");
                e.printStackTrace();
            

        

        @Override
        public void onFailure(Throwable t) 
            Log.d("onFailure", t.toString());
        
    );

如何在 json 中获取“posts”数组?我已经尝试过如上面的程序所示。 谁能帮帮我。在上面的程序中,我只想获取android中的posts数组。

    "posts": [

    "id": 343,
    "type": "post",
    "slug": "nk-advertising",
    "url": "https://btownmedia.com/2018/10/10/nk-advertising/",
    "status": "publish",
    "title": "NK Advertising",
    "title_plain": "NK Advertising",
    "content": "<p style=\"color: #7a6666; font-family: roboto-regular-webfont; font-size: 14px; line-height: 24px; margin: 0px; padding: 0px 0px 19px; width: 370px;\"><strong>Online advertisement:</strong> <em>Online advertisement on our website</em> means our basic service. Your business card or a visiting card sized advertisement is displayed on our website for pre-mentioned time frame.</p>\n<p style=\"color: #7a6666; font-family: roboto-regular-webfont; font-size: 14px; line-height: 24px; margin: 0px; padding: 0px 0px 19px; width: 370px;\"><strong>Personalized page:</strong> We offer you a personalized page, designed for your business with all the details of your business- linked with your advertisement that opens when clicked.</p>\n",
    "excerpt": "<p>Online advertisement on our website means our basic service. Your business card or a visiting card sized advertisement is displayed on our website for pre-mentioned time frame.</p>\n",
    "date": "2018-10-10 08:08:29",
    "modified": "2018-10-10 08:08:29",
    "categories": [
        
            "id": 44,
            "slug": "flex-print",
            "title": "Flex Print",
            "description": "Flex Print",
            "parent": 7,
            "post_count": 1
        
    ],
    "tags": [],
    "author": 
        "id": 1,
        "slug": "admin",
        "name": "admin",
        "first_name": "",
        "last_name": "",
        "nickname": "admin",
        "url": "",
        "description": ""
    ,
    "comments": [],
    "attachments": [
        
            "id": 342,
            "url": "https://btownmedia.com/nk/",
            "slug": "nk",
            "title": "nk",
            "description": "",
            "caption": "",
            "parent": 343,
            "mime_type": "image/png",
            "images": 
                "full": 
                    "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
                    "width": 230,
                    "height": 142
                ,
                "thumbnail": 
                    "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk-150x142.png",
                    "width": 150,
                    "height": 142
                ,
                "medium": 
                    "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
                    "width": 230,
                    "height": 142
                ,
                "medium_large": 
                    "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
                    "width": 230,
                    "height": 142
                ,
                "large": 
                    "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
                    "width": 230,
                    "height": 142
                ,
                "rpggallery_admin_thumb": 
                    "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
                    "width": 230,
                    "height": 142
                ,
                "rpggallery_admin_large": 
                    "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
                    "width": 230,
                    "height": 142
                ,
                "rpg_gallery_admin_thumb": 
                    "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk-150x142.png",
                    "width": 150,
                    "height": 142
                ,
                "rpg_gallery_thumb": 
                    "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk-150x142.png",
                    "width": 150,
                    "height": 142
                ,
                "estore-featured-image": 
                    "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
                    "width": 230,
                    "height": 142
                ,
                "estore-product-grid": 
                    "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk-75x75.png",
                    "width": 75,
                    "height": 75
                ,
                "estore-square": 
                    "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
                    "width": 230,
                    "height": 142
                ,
                "estore-slider": 
                    "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
                    "width": 230,
                    "height": 142
                ,
                "estore-medium-image": 
                    "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
                    "width": 230,
                    "height": 142
                
            
        
    ],
    "comment_count": 0,
    "comment_status": "open",
    "thumbnail": "https://btownmedia.com/wp-content/uploads/2018/10/nk-150x142.png",
    "custom_fields": ,
    "thumbnail_size": "thumbnail",
    "thumbnail_images": 
        "full": 
            "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
            "width": 230,
            "height": 142
        ,
        "thumbnail": 
            "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk-150x142.png",
            "width": 150,
            "height": 142
        ,
        "medium": 
            "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
            "width": 230,
            "height": 142
        ,
        "medium_large": 
            "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
            "width": 230,
            "height": 142
        ,
        "large": 
            "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
            "width": 230,
            "height": 142
        ,
        "rpggallery_admin_thumb": 
            "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
            "width": 230,
            "height": 142
        ,
        "rpggallery_admin_large": 
            "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
            "width": 230,
            "height": 142
        ,
        "rpg_gallery_admin_thumb": 
            "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk-150x142.png",
            "width": 150,
            "height": 142
        ,
        "rpg_gallery_thumb": 
            "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk-150x142.png",
            "width": 150,
            "height": 142
        ,
        "estore-featured-image": 
            "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
            "width": 230,
            "height": 142
        ,
        "estore-product-grid": 
            "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk-75x75.png",
            "width": 75,
            "height": 75
        ,
        "estore-square": 
            "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
            "width": 230,
            "height": 142
        ,
        "estore-slider": 
            "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
            "width": 230,
            "height": 142
        ,
        "estore-medium-image": 
            "url": "https://btownmedia.com/wp-content/uploads/2018/10/nk.png",
            "width": 230,
            "height": 142
        
    

]

【问题讨论】:

您的 JSON 格式似乎有误,这将使 ant 解析器难以完成工作,请先修复 JSON。 【参考方案1】:

最简单的解决方案是为您的 api 返回的整个对象创建一个上层类,然后从中获取您的帖子?

类似:

class APIResponse 
    public List<Post> posts;

    // add the other fields from your response if you need them

那么你只需要用

替换你的电话
@GET("json=get_category_posts&slug=flex-print&status=publish")
Call<APIResponse> getListPost();

然后您就可以轻松访问帖子列表,例如response.posts

但是,如果您不想拥有上层阶级而是直接拥有帖子列表,则可能需要使用自定义反序列化器。像这样的:

public static class PostAdapter implements JsonDeserializer<List<Post>> 
    public List<Post> deserialize(JsonElement jsonElement, Type typeOfT, JsonDeserializationContext ctx) 
        JsonObject json = jsonElement.getAsJsonObject();
        List<Post> vals = new ArrayList<>();
        if (json.has("posts") && .json.get("posts").isJsonArray()) 
            for (JsonElement e : json.get("posts").getAsJsonArray()) 
                vals.add((Post) ctx.deserialize(e, Post.class));
            
         
        return vals;
    

您可以在创建改造服务时注册到您的 gson 构建器:

Type postListType = new TypeToken<List<Post>>() .getType();

Gson gson = new GsonBuilder()
        .registerTypeAdapter(postListType, new PostAdapter())
        .create();
Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url1)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();

通过这样做,每次您在 interfaceAPI 中声明一个 Call> 时,它将使用此适配器来获得正确的结果。所以现在你可以做

@GET("json=get_category_posts&slug=flex-print&status=publish")
Call<List<Post>> getListPost();

【讨论】:

【参考方案2】:

Post.java

public class Post 
private Integer id;
private String type;
private String slug;
private String url;
private String status;
private String title;
private String titlePlain;
private  String content;
private  String excerpt;
private String thumbnail;


public Integer getId() 
    return id;


public void setId(Integer id) 
    this.id = id;


public String getType() 
    return type;


public void setType(String type) 
    this.type = type;


public String getSlug() 
    return slug;


public void setSlug(String slug) 
    this.slug = slug;


public String getUrl() 
    return url;


public void setUrl(String url) 
    this.url = url;


public String getStatus() 
    return status;


public void setStatus(String status) 
    this.status = status;


public String getTitle() 
    return title;


public void setTitle(String title) 
    this.title = title;


public String getTitlePlain() 
    return titlePlain;


public void setTitlePlain(String titlePlain) 
    this.titlePlain = titlePlain;


public String getContent() 
    return content;


public void setContent(String content) 
    this.content = content;


public String getExcerpt() 
    return excerpt;


public void setExcerpt(String excerpt) 
    this.excerpt = excerpt;


public String getThumbnail() 
    return thumbnail;


public void setThumbnail(String thumbnail) 
    this.thumbnail = thumbnail;

PostArtical.java

public class PostArtical 
private String status;
private Integer count;
private Integer pages;
private Category category;
private List<Post> posts = null;


public String getStatus() 
    return status;


public void setStatus(String status) 
    this.status = status;


public Integer getCount() 
    return count;


public void setCount(Integer count) 
    this.count = count;


public Integer getPages() 
    return pages;


public void setPages(Integer pages) 
    this.pages = pages;


public Category getCategory() 
    return category;


public void setCategory(Category category) 
    this.category = category;


public List<Post> getPosts() 
    return posts;


public void setPosts(List<Post> posts) 
    this.posts = posts;

Category.java

public class Category 

private Integer id;
private String slug;
private String title;
private String description;
private Integer parent;
private Integer postCount;

public Integer getId() 
    return id;


public void setId(Integer id) 
    this.id = id;


public String getSlug() 
    return slug;


public void setSlug(String slug) 
    this.slug = slug;


public String getTitle() 
    return title;


public void setTitle(String title) 
    this.title = title;


public String getDescription() 
    return description;


public void setDescription(String description) 
    this.description = description;


public Integer getParent() 
    return parent;


public void setParent(Integer parent) 
    this.parent = parent;


public Integer getPostCount() 
    return postCount;


public void setPostCount(Integer postCount) 
    this.postCount = postCount;

MainActivity.java

//onCreate方法内部

  onCreate method

getRetrofitPostObject();

//在onCreate方法之外

 void getRetrofitPostObject() 

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(urlp)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

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

    Call<PostArtical> call = service.getPostDetails();

    call.enqueue(new Callback<PostArtical>() 
        @Override
        public void onResponse(Response<PostArtical> response, Retrofit retrofit) 

            try 
                    Log.d("Category", response.body().getCategory().getTitle());

                Log.d("PostText", response.body().getPosts().get(0).getTitle());

                List<Post> PostData = response.body().getPosts();



                for (int i = 0; i < PostData.size(); i++) 

                    if (i == 0) 
                        text_id_1.setText("id  :  " + PostData.get(i).getId());
                        Log.d("Atrical[0]", String.valueOf(PostData.get(i).getId()));
                        Log.d("Atrical[title]", String.valueOf(PostData.get(i).getTitle()));
                        Log.d("Atrical[content]", String.valueOf(PostData.get(i).getContent()).replaceAll("(<[^>]+>)|(&[^;]+;)",""));

                        Log.d("Atrical[Excerpt]", String.valueOf(PostData.get(i).getExcerpt()).replaceAll("(<[^>]+>)|(&[^;]+;)",""));
                        Log.d("Atrical[image]", String.valueOf(PostData.get(i).getThumbnail()));
                        img = PostData.get(i).getThumbnail();

                       DownloadImageWithURLTask downloadTask = new DownloadImageWithURLTask(imageview);
                        downloadTask.execute(img);



                        // text_name_1.setText("title  :  " + StudentData.get(i).getTitle());

                    
                


              //  text_id_1.setText("PostStatus  :  " + response.body().getStatus());
                text_name_1.setText("PostCount  :  " + response.body().getCount());
                text_marks_1.setText("PostPage  : " + response.body().getPages());

             catch (Exception e) 
                Log.d("onResponse", "There is an error");
                e.printStackTrace();
            

        

        @Override
        public void onFailure(Throwable t) 
            Log.d("onFailure", t.toString());
        
    );

【讨论】:

以上是关于如何使用改造 2 在 Android 中获取 Json,如下面的代码所示?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 rx 从改造中获取请求 url? - 安卓

Android - 改造 2 - 身份验证器结果

在 Android 中通过改造获取对象数组

Android - 使用改造和协程获取响应状态代码

oAuth 1.0 获取请求改造 android

如何访问数组改造 2 / android studio 中的对象“播放器”