-2

I'm just starting to learn how to use JSON in Android. I'm supposed to make an app that display news title, section and author.

I'm not really sure if the problem is in the parsing or something else but it keeps telling me there's no data.

So can I get some help with this part if it has a problem so I can fix it or go look more to where the problem is.

the JSON code:

{
   "response": {
        "status": "ok",
        "userTier": "developer",
        "total": 191,
        "startIndex": 1,
        "pageSize": 10,
        "currentPage": 1,
        "pages": 20,
        "orderBy": "relevance",
        "results": [{
            "id": "film/2017/may/25/12-jours-review-raymond-depardon-documentary-psychiatric-hospital-judge",
            "type": "article",
            "sectionId": "film",
            "sectionName": "Film",
            "webPublicationDate": "2017-05-25T15:37:15Z",
            "webTitle": "12 Jours review – a devastating glimpse into broken souls",
            "webUrl": "https://www.theguardian.com/film/2017/may/25/12-jours-review-raymond-depardon-documentary-psychiatric-hospital-judge",
            "apiUrl": "https://content.guardianapis.com/film/2017/may/25/12-jours-review-raymond-depardon-documentary-psychiatric-hospital-judge",
            "fields": {
                "headline": "12 Jours review – a devastating glimpse into broken souls",
                "starRating": "4",
                "shortUrl": "https://gu.com/p/6g6hn",
                "thumbnail": "https://media.guim.co.uk/1dbf594e183ebe5428fe88c82784c55908b4753c/0_0_3598_2160/500.jpg"
            },
            "tags": [{
                "id": "profile/wendy-ide",
                "type": "contributor",
                "sectionId": "film",
                "sectionName": "Film",
                "webTitle": "Wendy Ide",
                "webUrl": "https://www.theguardian.com/profile/wendy-ide",
                "apiUrl": "https://content.guardianapis.com/profile/wendy-ide",
                "references": [],
                "firstName": "wendy",
                "lastName": "ide"
            }],
            "isHosted": false,
            "pillarId": "pillar/arts",
            "pillarName": "Arts"
        }]
    }
}

all I need is the title, section, author and the url. So I wrote it like this:

 private static List<News> extractFeatureFromJson(String newsJSON) {
    if (TextUtils.isEmpty(newsJSON)) {
        return null;
    }
    List<News> news = new ArrayList<>();
    try {


      JSONObject baseJsonResponse = new JSONObject(newsJSON);
        String response = baseJsonResponse.getString("response");
        JSONObject object = new JSONObject(response);;
        JSONArray newsArray=object.getJSONArray("results");
        for (int i = 0; i < newsArray.length(); i++) {
            JSONObject currentNews = newsArray.getJSONObject(i);
            JSONObject results = currentNews.getJSONObject("results");
            String title = results.getString("webTitle");
            String section = results.getString("sectionName");
            String author = results.getString("firstName");
            String url = results.getString("webUrl");

            News nNews = new News(title, section, author, url);

            news.add(nNews);
        }

    } catch (JSONException e) {
        Log.e("QueryUtils", "Problem parsing the news JSON results", e);
    }
    return news;
}

It's a new concept for me and I'm very confused, I'd really appreciate some help.

Edit:

I'm using a loader in the same app, if the list is empty it would display a string that there's no data and that's what it keeps on appearing. I have no idea what's the problem.

public void onLoadFinished(Loader<List<News>> loader, List<News> news) {
    View loadingIndicator = findViewById(R.id.loading_indicator);
    loadingIndicator.setVisibility(View.GONE);

    emptyTextView.setText(R.string.no_news);
    newsAdapter.clear();
    if (news != null && !news.isEmpty()) {
        newsAdapter.addAll(news);
    }
}
Gholamali Irani
  • 4,391
  • 6
  • 28
  • 59
NA- Chan
  • 1
  • 3

7 Answers7

0

Remove this line

String response = baseJsonResponse.getString("response");

And Change this line

    JSONObject object = new JSONObject(response);

To

    JSONObject object = baseJsonResponse.getJSONObject("response");
Munir
  • 2,548
  • 1
  • 11
  • 20
0

Try this code,

JSONObject baseJsonResponse = new JSONObject(newsJSON);
     JSONObject resJson =baseJsonResponse.getJSONObject("response");
     String status = resJson.getString("status");
JSONArray newsArray=resJson .getJSONArray("results");
Pratik18
  • 365
  • 1
  • 7
0

Replace this loop in ur code, everything else seems to be fine.

   private static List<News> extractFeatureFromJson(String newsJSON) {
        if (TextUtils.isEmpty(newsJSON)) {
            return null;
        }
        List<News> news = new ArrayList<>();
        try {
            JSONObject baseJsonResponse = new JSONObject(newsJSON);
            String response = baseJsonResponse.getString("response");
            JSONObject object = new JSONObject(response);;
            String status = object.getString("status");
            if(status.equals("ok")){
            JSONArray newsArray=object.getJSONArray("results");
            for (int i = 0; i < newsArray.length(); i++) {
                JSONObject currentNews = newsArray.getJSONObject(i);
                JSONObject results = currentNews.getJSONObject("results");
                String title = results.getString("webTitle");
                String section = results.getString("sectionName");
                String author = results.getString("firstName");
                String url = results.getString("webUrl");

                News nNews = new News(title, section, author, url);

                news.add(nNews);
            }
            }else{
                //Invalid response Toast here
            }

        } catch (JSONException e) {
            Log.e("QueryUtils", "Problem parsing the news JSON results", e);
        }
        return news;
    }
Pratim P
  • 169
  • 1
  • 5
0

your Json type is wrong! Brackets do not match

  • i didn't type it myself, i got it from here https://content.guardianapis.com/search?q=12%20years%20a%20slave&format=json&tag=film/film,tone/reviews&from-date=2010-01-01&show-tags=contributor&show-fields=starRating,headline,thumbnail,short-url&order-by=relevance&api-key=test – NA- Chan Jan 13 '18 at 06:15
  • wait 10 minute ! I will send you a code for parse this json –  Jan 13 '18 at 06:29
  • please see last post With that code you can parse Json The information I received was just a few items Get all items in response object and etc.. and get inside your model or list –  Jan 13 '18 at 06:48
0

use this code for extractFeatureFromJson

private static List<News> extractFeatureFromJson(String newsJSON) {
    if (TextUtils.isEmpty(newsJSON)) {
        return null;
    }
    List<News> news = new ArrayList<>();
    try {
        JSONObject baseJsonResponse = new JSONObject(newsJSON);
        String response = baseJsonResponse.getString("response");
        JSONObject object = new JSONObject(response);;
        JSONArray newsArray=object.getJSONArray("results");
        for (int i = 0; i < newsArray.length(); i++) {
            JSONObject currentNews = newsArray.getJSONObject(i);
            String title = currentNews.getString("webTitle");
            String section = currentNews.getString("sectionName");
            JSONArray tag = currentNews.getJSONArray("tags");
            String firstName;
            if(tag.length() != 0){
                firstName = tag.getJSONObject(0).getString("firstName");
            }
            String url = currentNews.getString("webUrl");

            News nNews = new News(title, section, author, url);

            news.add(nNews);
        }

    } catch (JSONException e) {
        Log.e("QueryUtils", "Problem parsing the news JSON results", e);
    }
    return news;
}
Gautam Chibde
  • 1,167
  • 3
  • 14
  • 27
0

You should not use JSONObject results = currentNews.getJSONObject("results"); because you alreade got the result array as JSONArray newsArray=object.getJSONArray("results"); try this

                for (int i = 0; i < newsArray.length(); i++) {            
                JSONObject results = newsArray.getJSONObject(i);
                String title = results.getString("webTitle");
                String section = results.getString("sectionName");
                String author = results.getString("firstName");
                String url = results.getString("webUrl");

                News nNews = new News(title, section, author, url);

                news.add(nNews);
            }
Kapil Parmar
  • 881
  • 8
  • 19
0
        try
        {

            JSONObject jsonObject = new JSONObject("Your_json");

            // get response object
            JSONObject jsonObjectResponse = jsonObject.getJSONObject("response");

            /*
                get Status string from jsonObjectResponse
                you can also get | userTier | total | startIndex and other strings in this json Object
             */
            String status = jsonObjectResponse.getString("status");

            // get result as Json array from jsonObjectResponse
            JSONArray jsonArrayResults = jsonObjectResponse.getJSONArray("results");
            for (int i = 0; i < jsonArrayResults.length() ; i++)
            {
                JSONObject jsonObjectResult = jsonArrayResults.getJSONObject(i);
                String id = jsonObjectResult.getString("id");
                String type = jsonObjectResult.getString("type");
                String sectionId = jsonObjectResult.getString("sectionId");
                String sectionName = jsonObjectResult.getString("sectionName");
                String webPublicationDate = jsonObjectResult.getString("webPublicationDate");
                String webTitle = jsonObjectResult.getString("webTitle");
                String webUrl = jsonObjectResult.getString("webUrl");
                String apiUrl = jsonObjectResult.getString("apiUrl");
                JSONObject jsonObjectfields = new JSONObject(jsonObjectResult.getString("fields"));
                String fieldHeadLine = jsonObjectfields.getString("headline");
                String fieldStarRating = jsonObjectfields.getString("starRating");
                String fieldShortUrl = jsonObjectfields.getString("shortUrl");
                String fieldThumbnail = jsonObjectfields.getString("thumbnail");

                JSONArray jsonArrayTags = jsonObjectResult.getJSONArray("tags");
                for (int j = 0; j < jsonArrayTags.length(); j++)
                {
                    JSONObject jsonObjectTags = jsonArrayTags.getJSONObject(j);
                    String tagID = jsonObjectTags.getString("id");
                    String tagType = jsonObjectTags.getString("type");
                    String tagSelectionID = jsonObjectTags.getString("sectionId");
                    String tagSectionName = jsonObjectTags.getString("sectionName");
                    // iam just get 4 string ! you can get all tags string with replacing
                }
                //** and get others  each jsonObject from result Array
            }



        }
        catch (JSONException e)
        {
            e.printStackTrace();
            // when parse json error happend! check log  cat 
        }

this code parse this link

I took only a few items from each part to clarify the case