通过改进从JSONObject获取JSONArray

时间:2018-03-03 15:22:24

标签: android json wordpress retrofit2

我正在使用Wordpress,我想获得自定义字段,但我无法找到任何可以获得它们的内容,或者如果可以的话,我能找到的最接近的答案是{{3}但是我无法理解我如何能够对我有利,我在使用retrofit2时是新手。你能告诉我是否有可能这样做,如果是这样的话怎么样? 以下是JSON回复我尝试使用

    {
  "status": "ok",
  "post": {
    "id": 748,
    "type": "post",
    "slug": "string",
    "url": string",
    "status": "publish",
    "title": "s",
    "title_plain": "",
    "content": "",
    "excerpt": "<p><\/p>\n",
    "date": "2017-11-03 12:43:53",
    "modified": "2018-02-27 20:15:43",
    "categories": [
      {
        "id": 3,
        "slug": "music",
        "title": "Music",
        "description": "",
        "parent": 0,
        "post_count": 134
      }
    ],
    "tags": [
      {
        "id": 9,
        "slug": "altezzaiscute24",
        "title": "AltezzaIscute24",
        "description": "",
        "post_count": 1
      },
      {
        "id": 7,
        "slug": "amv",
        "title": "AMV",
        "description": "",
        "post_count": 6
      },
      {
        "id": 4,
        "slug": "atlantic-records",
        "title": "Atlantic Records",
        "description": "",
        "post_count": 1
      },
      {
        "id": 8,
        "slug": "discord",
        "title": "Discord",
        "description": "",
        "post_count": 1
      },
      {
        "id": 5,
        "slug": "hero",
        "title": "Hero",
        "description": "",
        "post_count": 1
      },
      {
        "id": 10,
        "slug": "skillet",
        "title": "Skillet",
        "description": "",
        "post_count": 1
      },
      {
        "id": 6,
        "slug": "",
        "title": "",
        "description": "",
        "post_count": 1
      }
    ],
    "author": {
      "id": 1,
      "slug": "admin",
      "name": "admin",
      "first_name": "",
      "last_name": "",
      "nickname": "admin",
      "url": "",
      "description": ""
    },
    "comments": [
      {
        "id": 335,
        "name": "\u7231Neko",
        "url": "",
        "date": "2017-11-03 12:44:51",
        "content": "<p>Amazing..!! \ud83d\ude00<\/p>\n",
        "parent": 0
      },
      {
        "id": 334,
        "name": "AltezzaIscute24(Ex. importednascar)",
        "url": "",
        "date": "2017-11-03 12:45:35",
        "content": "<p>Nice one!<\/p>\n",
        "parent": 0
      },
      {
        "id": 333,
        "name": "NjustN",
        "url": "",
        "date": "2017-11-03 12:51:27",
        "content": "<p><\/p>\n",
        "parent": 
      }
    ],
    "attachments": [
      {
        "id": 1447,
        "url": "/",
        "slug": "",
        "title": "",
        "description": "",
        "caption": "",
        "parent": 748,
        "mime_type": "image\/jpeg",
        "images": {
          "full": {
            "url": "",
            "width": 1280,
            "height": 720
          },
          "thumbnail": {
            "url": ",
            "width": 150,
            "height": 150
          },
          "medium": {
            "url": "",
            "width": 300,
            "height": 169
          },

        }
      }
    ],
    "comment_count": 3,
    "comment_status": "open",
    "thumbnail": "",
    "custom_fields": {
      "yvtwp_video_datas": [
        "}"
      ],
      "yvtwp_video_key": [
        "h"
      ],
      "yvtwp_feed_key": [
        "j"
      ],
      "yvtwp_import_id": [
        "1"
      ],
      "tie_video_url": [
        "https:\/\/www.youtube.com\/watch?v="
      ],
      "tie_embed_code": [
        "<iframe width=\"100%\" height=\"315\" src=\"https:\/\/www.youtube.com\/embed\/\" frameborder=\"0\" allowfullscreen><\/iframe>"
      ],
      "tie_post_head": [
        "video"
      ],
      "tie_views": [
        "2160"
      ],
      "tie_post_head_cover": [
        "true"
      ],
      "post_background_full": [
        "true"
      ],
      "video_time": [
        "2:38"
      ],
      "video_likes": [
        "27"
      ],
      "yvtwp_count_synchronize_video_per_day": [
        "1"
      ],
      "yvtwp_synchronize_video_last_date": [
        "2018-02-27 20:15:44"
      ],
      "yvtwp_count_check_comments_per_day": [
        "1"
      ],
      "yvtwp_check_comments_last_date": [
        "2018-02-27 20:15:44"
      ],
      "yvtwp_views_count": [
        "18"
      ]
    },

  "previous_url": "/"
}

修改1 回答 Fazal Hussain 给了我试过,我收到了这个错误:

03-06 21:31:30.750 1455-1455/xyz.wizardsong102 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                 Process: xyz.wizardsong102, PID: 1455
                                                                 java.lang.NullPointerException: Attempt to read from field 'java.util.List com.xyz.wizardsong102.model.CustomFields.tieVideoUrl' on a null object reference
                                                                     at com.xyz.wizardsong102.ActivityPostDetails$2.onResponse(ActivityPostDetails.java:180)
                                                                     at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
                                                                     at android.os.Handler.handleCallback(Handler.java:739)
                                                                     at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                     at android.os.Looper.loop(Looper.java:148)
                                                                     at android.app.ActivityThread.main(ActivityThread.java:5422)
                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

这是我的活动:

callbackCall.enqueue(new Callback<CallbackDetailsPost>() {
            @Override
            public void onResponse(Call<CallbackDetailsPost> call, Response<CallbackDetailsPost> response) {
                CallbackDetailsPost resp = response.body();
               // Log.i(TAG, "response:w "+ post.customFields.tieVideoUrl);
                if (resp != null && resp.status.equals("ok")) {

                    //Log.d("json api res: ", "resposd: "+ resp);
                    post = resp.post;
                    displayPostData(false);

                    Log.i(TAG, "response:w "+ post.customFields.tieVideoUrl);
                    swipeProgress(false);
                } else {
                    String error = resp.status;
                    onFailRequest(error);
                }
            }

            @Override
            public void onFailure(Call<CallbackDetailsPost> call, Throwable t) {
                Log.d(TAG, "Faild: ", t);
                String error = t.toString();
                if (!call.isCanceled()) onFailRequest(error);
            }

        });
    }

编辑2:

Post.java

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import io.realm.RealmList;


public class Post implements Serializable {

    public int id = -1;
    public String type = "";
    public String slug = "";
    public String url = "";
    public String status = "";
    public String title = "";
    public String title_plain = "";
    public String content = "";
    public String excerpt = "";
    public String date = "";
    public String modified = "";
    public String thumbnail = "";
    public int comment_count = -1;
    public CustomFields customFields;

    public List<Category> categories = new ArrayList<>();
    public Author author = null;
    public List<Comment> comments = new ArrayList<>();
    public List<Attachment> attachments = new ArrayList<>();

    public PostRealm getObjectRealm() {
        PostRealm p = new PostRealm();
        p.id = id;
        p.type = type;
        p.slug = slug;
        p.url = url;
        p.status = status;
        p.title = title;
        p.title_plain = title_plain;
        p.content = content;
        p.excerpt = excerpt;
        p.date = date;
        p.modified = modified;
        p.thumbnail = thumbnail;
        p.comment_count = comment_count;


        p.categories = new RealmList<>();
        for (Category c : categories) { p.categories.add(c.getObjectRealm()); }



        p.comments = new RealmList<>();
        for (Comment c : comments) { p.comments.add(c.getObjectRealm()); }

        p.author = ( author != null ? author.getObjectRealm() : null );

        p.attachments = new RealmList<>();
        for (Attachment a : attachments) { p.attachments.add(a.getObjectRealm()); }


        return p;
    }

    public boolean isDraft(){
        return !(content != null && !content.trim().equals(""));
    }

}

CustomFields.java

import java.io.Serializable;
import java.util.List;

public class CustomFields implements Serializable
{

    public List<String> yvtwpVideoKey = null;
    public List<String> yvtwpFeedKey = null;
    public List<String> yvtwpImportId = null;
    public List<String> tieVideoUrl = null;
    public List<String> tieViews = null;
    public List<String> videoTime = null;
    public List<String> videoLikes = null;
}

编辑3 How to get JSON ARRAY and JSON object response from retrofit response?

1 个答案:

答案 0 :(得分:0)

使用Json to pojo scheme

https://www.google.com.pk/url?sa=t&source=web&rct=j&url=http://www.jsonschema2pojo.org/&ved=2ahUKEwjBgsKs0dDZAhUQy6QKHUuSCkMQFjAAegQICBAB&usg=AOvVaw2LRJc0bLRrE3xWYLEBf71U

这将为你的json

创建所有模型类

在您的活动中

Call<ServerResponse> call = service.getdata(); 
call.enqueue(new Callback<ServerResponse>() { 
@Override
public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) { 
    ServerResponse serverResponse = response.body();
    if (serverResponse != null) { 
        List<Categories> categoriesList = response.getCategory(); 
    } 
} 
@Override 
public void onFailure(Call<ServerResponse> call, Throwable t) { } });