简体   繁体   中英

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

how I could reach the object which is inside of array? I can enter the array, but I don't know how to go "deeper". Here's the dummy code, for testing purposes.

JSON response

    {
  "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;
        }
    }
}
}

MainActivity

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) {

        }
    });
}

Code, that I wrote in MainActivity, is responsible for getting Array, that I meantioned earlier. How I may reach the "source" object using retrofit? Can I have any prompt?

👋 Try this:

...
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();
...

It should simply be a matter of calling articles.getSource() to get the Source object. Does it return null, or what is the issue?

this is the code maybe help you

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;
}

}

You can Use Following Code to get Source Object Data from Retrofit Response.

First Declare List<Model.Articles> list Global. Then after create One Method Void method and Use this method whenever you want .

 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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM