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

exchange the class using only JavaScript

I need help with a code snippet that allows for swapping classes using a loop. The objective is to click on the brown square causing it to move to the position of the blue square, while the blue square moves to the previous position of the brown square. T ...

How can you conceal an object based on specific conditions in JavaScript?

In my JavaScript code, I am working with an object that stores multiple values. However, I want to be able to hide a specific object under certain conditions. Here is the data structure: $scope.sort={ National : { prop: "Country", classes: { md: ...

What are the steps to install node.js on hosting servers like Hostinger, JustHost, and others?

Recently, I've been diving into the world of Node.js. While I have some experience with PHP, I've found that most hosting services already have a PHP interpreter installed, making it easy to work with. However, I'm now trying to figure out i ...

Setting the column width and border-top in Highcharts

Hey there, I'm facing an issue with my highcharts diagram. 1) Can anyone help me adjust the column width to match the width of the month area? (I've tried changing "width" in CSS but it's not working) 2) Also, how can I remove all borders ...

Unexpected JSON data received compared to JSON data sent in Spring Rest and Hibernate

I'm facing challenges with integrating Spring Rest and Hibernate into my Android application. Specifically, I am encountering an issue with one of the POST calls in my API requests. In my project, I have two main classes: Player and Game. @Entity @T ...

The column in Pandas that contains JSON data is refusing to split into multiple columns, causing a JSONDecodeError

Having an issue with processing a large csv file (40GB) using pandas and JSON. The file consists of two columns, “id” and “data”. The second column contains json data which needs to be converted into separate columns. However, encountering the foll ...

Understanding how to translate the content of email confirmation and password reset pages in Parse Server

Is there a way to translate the Email Confirmation and Password Reset pages in my project using Parse server? I have searched everywhere for a solution but haven't found one yet. While I did come across information about email templates, I couldn&apos ...

Encountering the "node:internal/modules/cjs/loader:1050" error while attempting to execute a folder using the "npm run dev" command

I am encountering an issue while attempting to execute a folder using npm run dev, consistently resulting in the same error message. PS C:\Users\My Name\Desktop\My Folder> npm run dev Debugger attached. > <a href="/cdn-cgi/l/e ...

The parameter always comes up empty when using $state.go in AngularJS

When trying to pass one parameter using `$stete.go`, I encountered an issue. ROUTER $stateProvider.state('login.signin', { url: '/signin', params: { login_event: '' }, templateUrl: "assets/views/login ...

Toggle visibility of div based on current business hours, incorporating UTC time

UPDATE I have included a working JSFiddle link, although it appears to not be functioning correctly. https://jsfiddle.net/bill9000/yadk6sja/2/ original question: The code I currently have is designed to show/hide a div based on business hours. Is there a ...

What is the process of synchronizing state in react.js?

I am struggling to update the state and component in my code. When I press a button and change the value of one of the props in the popup component, the prop value does not get updated. I suspect this issue is due to using setState. I researched a possible ...

Need help incorporating a "section trail" into your website's navigation sidebar using JS/jquery? Here's how you can do it!

My website is quite extensive and contains numerous elements. There are times when I find myself wanting to navigate back and forth between different sections of the page. I've noticed that some websites have a feature called a "page trail," which di ...

Show a preview of an image in an HTML document

How can I display an image after uploading it? I attempted to use the following code, but it didn't work: onFileSuccess: function(file, response) { var json = new Hash(JSON.decode(response, true) || {}); if (json.get('status& ...

Navigating Form Submission in Next.js

In this code snippet, I attempted to perform simple addition (ket=name + names). The desired outcome is a numerical sum displayed as “ket”. However, when entering 3 and 6 into the input fields, the result appears as 36 instead of 9. export default fu ...

Are you experimenting with a web application by utilizing jUnit or another API?

Is it feasible to develop a testing suite for evaluating a web application with the junit API without incorporating additional APIs or considering alternative options? Can this also handle ajax, jquery, and javascript components? In other words, will I b ...

The form within the while loop is only functioning with the initial result

Within a while loop, I have a form that is being processed with ajax. The issue is that it only works on the first form and not on the others. Can someone take a look? <?php while($a = $stmt->fetch()){ ?> <form method="post" action=""> ...

Is there a reason behind why this functionality is only applicable to a class component and not a functional one?

Essentially, I am working with multiple buttons and aiming for the user to be able to select more than one button at a time. I attempted to achieve this using a functional component by storing the button states as objects with the useState hook. While the ...

An error message 'module.js:557 throw err' appeared while executing npm command in the terminal

Every time I try to run npm in the terminal, I encounter this error message and it prevents me from using any npm commands. This issue is also affecting my ability to install programs that rely on nodejs. $ npm module.js:557 throw err; ^ Error: Cannot ...

Is there a Java-based solution for encapsulating Cloudfoundry's VCAP_SERVICE?

When working with the VCAP_SERVICE environment variable using java.lang.System.getenv("VCAP_SERVICES"), it is necessary to manage a JSON String that may have a complex structure but follows a predictable pattern. Is there a popular helper class available ...

What is the best way to guide users to a different page once they have submitted form data

On my website, users have the ability to create bundles and include custom or predefined tasks within them. Everything functions properly, allowing for fields to be edited as needed. Once satisfied with the entries, users must click the "Save" button. Upon ...