Having trouble extracting the date modified from a JSON file

I am able to retrieve section name, URL, web title, and headline from parsing JSON data with this code snippet. However, I seem to be encountering an issue where I cannot extract the last modified date. Here is the JSON structure:

{  
   "response":{  
      "status":"ok",
      "userTier":"developer",
      "total":368,
      "startIndex":1,
      "pageSize":10,
      "currentPage":1,
      "pages":37,
      "orderBy":"relevance",
      "results":[  
         {  
            "id":"technology/2017/may/24/fitness-trackers-out-of-step-when-measuring-calories-research-shows",
            "type":"article",
            "sectionId":"technology",
            "sectionName":"Technology",
            "webPublicationDate":"2017-05-24T15:00:24Z",
            "webTitle":"Fitness trackers out of step when measuring calories, research shows",
            "webUrl":"https://www.theguardian.com/technology/2017/may/24/fitness-trackers-out-of-step-when-measuring-calories-research-shows",
            "apiUrl":"https://content.guardianapis.com/technology/2017/may/24/fitness-trackers-out-of-step-when-measuring-calories-research-shows",
            "fields":{  
               "headline":"Fitness trackers out of step when measuring calories, research shows",
               "lastModified":"2017-05-24T15:02:19Z",
               "thumbnail":"https://media.guim.co.uk/8d3e17604195078ec89e20329e2ddc5027eca8ea/0_213_6362_3817/500.jpg"
            },
            "isHosted":false
         },

Below is my code for parsing the JSON data:

JSONObject response = root.getJSONObject("response");

        if(response.has("results")){

            JSONArray results = response.getJSONArray("results");
            for(int i=0;i<results.length();i++){
                long lastModified=0;
                String headline=null;
                JSONObject details=results.getJSONObject(i);
                String sectionName=details.getString("sectionName");
                Log.i(LOG_TAG,sectionName);
                String webUrl=details.getString("webUrl");
                Log.i(LOG_TAG,webUrl);
                if(details.has("fields")){
                JSONObject fields=details.getJSONObject("fields");
                    if(fields.has("headline")){

                 headline =fields.getString("headline");
                Log.i(LOG_TAG,headline);}
                if(fields.has("lastModified")){
                 lastModified =fields.getLong("lastModified");
                Log.i(LOG_TAG, String.valueOf(lastModified));}}

Despite implementing this code, I am unable to retrieve the last modified date. I am unsure of why this particular information is not being successfully extracted.

Answer №1

Extracting Json data and retrieving the lastModified timestamp can be achieved with the following code snippet:

public static void parseJsonData(String jsonResponse) {
    try {
        JSONObject baseObject = new JSONObject(jsonResponse);

        if (baseObject == null) {
            return;
        }

        JSONObject responseObj = baseObject.optJSONObject("response");

        if (responseObj == null) {
            return;
        }

        JSONArray resultsArray = responseObj.getJSONArray("results");

        if (resultsArray == null) {
            return;
        }

        for (int i = 0; i < resultsArray.length(); i++) {
            JSONObject resultObj = resultsArray.getJSONObject(i);

            if (resultObj == null) {
                continue;
            }

            String id = resultObj.optString("id", "");
            String type = resultObj.optString("type", "");
            String sectionId = resultObj.optString("sectionId", "");
            String sectionName = resultObj.optString("sectionName", "");
            String webPublicationDate = resultObj.optString("webPublicationDate", "");
            String webTitle = resultObj.optString("webTitle", "");
            String webUrl = resultObj.optString("webUrl", "");
            String apiUrl = resultObj.optString("apiUrl", "");
            boolean isHosted = resultObj.optBoolean("isHosted", false);

            JSONObject fieldsObj = resultObj.optJSONObject("fields");

            if (fieldsObj == null) {
                continue;
            }

            String headline = fieldsObj.optString("headline", "");
            String lastModified = fieldsObj.optString("lastModified", "");
            String thumbnail = fieldsObj.optString("thumbnail", "");
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
}

If you need to format a date string into a specific pattern, use this method:

public static String formatDate(String inputDateStr) {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz");

    Date date = null;
    try {
        date = simpleDateFormat.parse(inputDateStr);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    if (date == null) {
        return "";
    }

    SimpleDateFormat convertedDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    return convertedDateFormat.format(date);
}

Answer №2

The DateTime format being used here is ISO 8601 DateTime, which JSON does not have a specific format for dates/times. If you take some time to search online, you will come across several implementations that can help parse it in Java.

Check out this resource for one of them.

If you are willing to explore alternatives to Java's Date/Time/Calendar classes, I recommend considering Joda Time. They provide various functionalities including the ability to parse strings like these using ISODateTimeFormat.

Answer №3

It's important to note that when using the code snippet

lastModified =fields.getLong("lastModified");
, it might be more appropriate to utilize getString() instead. This is due to the fact that your lastModified date appears to be of String Type.

Answer №4

This Java program defines a class for handling news articles.


public class News {
    private String title;
    private String sectionName;
    private String url;
    private String date;

    // Constructor
    public News(String title, String sectionName, String date, String url) {
        this.title = title;
        this.sectionName = sectionName;
        this.date = date;
        this.url = url;
    }

    // Overloaded constructor
    public News(String title, String sectionName) {
        this.title = title;
        this.sectionName = sectionName;
    }
    
    // Get methods
    public String getTitle() {
        return title;
    }

    public String getSectionName() {
        return sectionName;
    }

    public String getUrl() {
        return url;
    }

    public String getDate() {
        return date;
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The button colors in Material Ui do not update properly after switching themes

React Material UI is being utilized in this project. Although the theme is being overridden, the colors of buttons and inputs remain unchanged. Here is how the Material UI theme is created in theme.js // @flow import { createMuiTheme } from '@materi ...

Experience the mesmerizing motion of a D3.js Bar Chart as it ascends from the bottom to the top. Feel free to

Here is the snippet of code I am working with. Please check the link for the output graph demonstration. [Click here to view the output graph demo][1] (The current animation in the output is from top to bottom) I want to animate the bars from Bottom to ...

unable to locate the font file I recently downloaded in the Windows terminal

Interested in customizing your Windows terminal? I recently decided to change my font style and downloaded the desired one. However, despite seeing the font in control panel and trying the "downloading for every user" option, my terminal still can't l ...

Implementing conditional button visibility in Angular based on user authorization levels

I've been experimenting with the following code snippet: <button ng-if="!isAuthenticated()" ng-click="deleteReview()">Delete</button> In my JavaScript, I have: $scope.isAuthenticated = function() { $http.get("api/user ...

Retrieve the border color using Selenium WebDriver

Hey everyone, I'm currently trying to retrieve the border color of an extjs 4.2 form control text field using the getCssValue method. However, I'm having trouble getting the value as it's coming back blank. Below is a sample of my code that ...

How to bypass validation for required input in jQuery validate plugin

As an example, consider the <input name="surname" id="surname" type="text">. Sometimes I want to hide this input and make it non-required. My current workaround is to set a value such as "some value" when hiding the input, and then remove this value ...

Android Gmail Application: Implementing 1px horizontal spacing between inline images placed within <td> tags

Have you ever noticed that in the Android Gmail app, there can be a mysterious 1px gap between inline images? This little pixel problem can sometimes push the rightmost image outside the comfy frame of your email. It seems this glitch prefers images of cer ...

Tips for retrieving a parameter from the oncomplete attribute of an a4j:jsFunction tag

Is it possible to access a parameter for an <a4j:jsFunction> in the oncomplete="" attribute without using the action="" attribute and assingTo="" of <a4j:param>? <a4j:jsFunction name="refreshTableFilter" render="table,scroller" execute="@fo ...

Creating a properly formatted JSON output for Java Jersey REST API by displaying the contents of an ArrayList

As I develop a Restful API that will provide responses in JSON format, I encounter an issue with converting data from an arrayList. The straightforward solution appears to be using the built-in method toJSONString(), but this results in a JSON string con ...

Generating a Random Number Within a Specified Range

function generateRandomNumberBetween(start, stop) { var low = Math.ceil(low); var high = Math.floor(high); return Math.floor(Math.random() * (high - low + 1)) + min; } function testRandomNumberGeneration() { var start = parseInt(prompt("Enter low ...

Utilizing namespacing in a JavaScript library can enhance organization and flexibility, providing

Creating a JavaScript library with multiple modules is my next project. Imagine the library is named Library, with modules One and Two. My goal is to allow end users to call the library in two ways: Library.One.somefunction(params) or somefunction(param ...

Learn how to increase a value with each dynamically clicked button in JavaScript

Whenever I try to increment the value by clicking the like button, it seems to be increasing but not in sync with the actual button count. How can I fix this issue? index.html <div class="row"> <div class="col-md-4"> ...

Is React State with JSON Object Losing Updates?

Encountering a strange issue here. At the start of my program, I load various values into a JSON object stored as a User State Object in a Postgres table. Although the object is quite large, I'll provide an example below. const [person, setPerson] = u ...

Connect and interact with others through the Share Dialogues feature in the

Update - Edit I'm just starting to explore the concept of share dialogues and I want to integrate it into my website. On my site, there is a reaction timer game that shows the user's reaction time in seconds in a modal popup. I want users to be ...

Shifting the MUI DataGrid Pagination table to the left with CustomPagination: A step-by-step guide

Hey everyone, I am currently diving into the MUI data grid to gain a better understanding. In order to meet my design requirements for a table view, I have incorporated the DataGrid component from MUI. For pagination, I am utilizing their custom implementa ...

Add the hue value from Hue into the Chromajs HSL state value

My objective is to dynamically change the background color of a div based on user input. I plan to assign the user's input as the value of the state key hue, and then set another state key called color to hold the HSL representation of the hue using C ...

Adjustable Scroll Bar

Could anyone help me find a component similar to the resizable scrollbar on Google Finance? Check out this link: http://www.google.com/finance?q=EURUSD&ei=bhM_UKDXF-aIWqAPVNQ You can see it below the chart. If you know where I can find something like ...

Battle of Kingdoms API ajax

When attempting to access Clash of Clans API information in this script, the following error is encountered: Refused to execute script from 'https://api.clashofclans.com/v1/leagues?authorization=Bearer%20eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiIsImtpZCI6Ij ...

Guide to securely encrypting passwords when transferring from an Android device to a PHP server

As a beginner in programming, I am currently working on a small application running on an Android device that requires user-based information from my PHP web server. My strategy involves using JSON for communication between the phone and the server. The p ...

Utilize JSON Objects rather than JSON arrays when using JSON-SERVER

Currently, I am utilizing json-server to transform JSON data into a REST API. Whenever a GET request is made like this: http://localhost:3000/items?itemid=534 The server responds with: [ { "itemid": 534, "type": "textcontent", "icon": "ht ...