簡體   English   中英

如何獲取JSON數組內部的JSON對象

[英]How do I get the JSON object which is inside of JSON array

我怎樣才能到達數組內部的對象? 我可以輸入數組,但是我不知道如何“更深入”。 這是用於測試目的的偽代碼。

JSON回應

    {
  "status": "xxx",
  "totalResults": 000,
  "articles": [
    {
      "source": {
        "id": xxx,
        "name": "xxx"
      },
      "author": "xxx",
      "title": "xxx",
      "description": "xxx",
      "url": "xxx",
      "urlToImage": "xxx",
      "publishedAt": "xxx",
      "content": "xxx"
    }
  ]
}

POJO

public class Model {

@SerializedName("status")
private String status;
@SerializedName("totalResults")
private int totalResults;
@SerializedName("articles")
List<Articles> getArticlesData = null;

public String getStatus() {
    return status;
}

public int getTotalResults() {
    return totalResults;
}

public List<Articles> getGetArticlesData() {
    return getArticlesData;
}

public class Articles {

    @SerializedName("author")
    private String author;
    @SerializedName("title")
    private String title;
    @SerializedName("description")
    private String description;
    @SerializedName("url")
    private String url;
    @SerializedName("urlToImage")
    private String imageUrl;
    @SerializedName("publishedAt")
    private String publishedAt;
    @SerializedName("content")
    private String content;
    @SerializedName("source")
    private Source source;


    public String getAuthor() {
        return author;
    }

    public String getTitle() {
        return title;
    }

    public String getDescription() {
        return description;
    }

    public String getUrl() {
        return url;
    }

    public String getImageUrl() {
        return imageUrl;
    }

    public String getPublishedAt() {
        return publishedAt;
    }

    public String getContent() {
        return content;
    }

    public Source getSource() {
        return source;
    }

    public class Source {

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

        public String getId() {
            return id;
        }

        public String getName() {
            return name;
        }
    }
}
}

主要活動

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://newsapi.org/v2/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    testApi api = retrofit.create(testApi.class);
    Call<Model> call = api.getNews("xxx","xxx");
    call.enqueue(new Callback<Model>() {
        @Override
        public void onResponse(Call<Model> call, Response<Model> response) {
            if (!response.isSuccessful()) {
                Toast.makeText(MainActivity.this, response.code(), Toast.LENGTH_SHORT).show();
            }

            List<Model.Articles> list = response.body().getGetArticlesData();
                for (Model.Articles articles : list){
                    String a = "";
                    a += articles.getAuthor()+"\n";
                    a += articles.getTitle()+"\n";
                    a += articles.getDescription()+"\n";
                    a += articles.getUrl()+"\n";
                    a += articles.getImageUrl()+"\n";
                    a += articles.getPublishedAt()+"\n";
                    a += articles.getContent()+"\n\n\n";
                    textView.append(a);
                }
        }
        @Override
        public void onFailure(Call<Model> call, Throwable t) {

        }
    });
}

我在MainActivity中編寫的代碼負責獲取Array(我早先曾說過)。 如何通過改型達到“源”對象? 我可以提示嗎?

👋試試這個:

...
List<Model.Articles> list = response.body().getGetArticlesData();

//Here we can get specific `Source` object by number 1
Source source = list.get(0).getSource();
String nameSource = source.getName();
...

只需調用articles.getSource()以獲取Source對象即可。 它返回null還是問題?

這是代碼可能會幫助您

private final static String KEY_NAME = "name";
private final static String KEY_MAIN_NAME = "mainName";
private final static String KEY_ALSO_KNOWN_AS = "alsoKnownAs";
private final static String KEY_PLACE_OF_ORIGIN = "placeOfOrigin";
private final static String KEY_DESCRIPTION = "description";
private final static String KEY_IMAGE_URL = "image";
private final static String KEY_INGREDIENTS = "ingredients";

public static Sandwich parseSandwichJson(String json) throws JSONException {
    JSONObject sandwichObject = new JSONObject(json);

    // name object
    JSONObject name = sandwichObject.getJSONObject(KEY_NAME);

    // mainName
    String mainName = name.getString(KEY_MAIN_NAME);

    // Also known as
    JSONArray alsoKnownAs = name.getJSONArray(KEY_ALSO_KNOWN_AS);
    List<String> knowAs = getStrings(alsoKnownAs);

    // Place of origin
    String placeOfOrigin = sandwichObject.getString(KEY_PLACE_OF_ORIGIN);

    // Description
    String description = sandwichObject.getString(KEY_DESCRIPTION);

    // Image
    String image = sandwichObject.getString(KEY_IMAGE_URL);

    // Ingredients
    JSONArray ingredientsJson = sandwichObject.getJSONArray(KEY_INGREDIENTS);
    List<String> ingredients = getStrings(ingredientsJson);

    return new Sandwich(mainName, knowAs, placeOfOrigin, description, image, ingredients);
}
private static List<String> getStrings(JSONArray jsonArray) throws JSONException {
    List<String> strings = new ArrayList<>();
    for (int i = 0; i < jsonArray.length(); i++) {
        strings.add(jsonArray.getString(i));
    }
    return strings;
}

}

您可以使用以下代碼從翻新響應中獲取源對象數據。

首先聲明List<Model.Articles> list全局。 然后,在創建一個方法無效方法之后,並在需要時使用此方法

 private void fetchMySouurceData() {
    for(int i=0;i<list.size();i++){
        Source currentSource=list.get(i).getSource();
        String id=currentSource.getid();
        String name=currentSource.getname();
        Log.i("CurrentSource", "Source: "+(i+1)+" \n id is: "+id+" & Name is: "+name);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM