Failure to properly parse dates when using String Parse, JSON Stringify, and GSON Parse

Converting a String into a Javascript object can be done using the following code:

{
"startTime": 233432420233,
"endTime": 233432431000,
"bufferingDelays": [
    {
        "time": 233432420233,
        "delayLength": 100
    },
    {
        "time": 233432420433,
        "delayLength": 50
    },
    {
        "time": 233432420833,
        "delayLength": 75
    }
    ]
}

The parsing and conversion process is shown in the Javascript code snippet below:

var reportObject = jQuery.parseJSON(reportJSONString);

reportObject.startTime = new Date(reportObject.startTime);
reportObject.endTime = new Date(reportObject.endTime);

for (var i = 0; i < reportObject.bufferingDelays.length; i++)
{                        
    var delay = reportObject.bufferingDelays[i];
    delay.time = new Date( delay.time );

    reportObject.bufferingDelays[i] = delay;
}

var reportObjectFinalString = JSON.stringify( reportObject );

If you encounter an issue with dates having trailing 'Z' when converting to JSON, consider revising the format.

In Java, the parsing of the JSON data into a Java Object can be achieved using the Gson library as demonstrated below:

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").create();
Report report = gson.fromJson( jsonBuilder.toString(), Report.class );   

However, ensure that the date format matches for successful conversion without exceptions.

Answer №1

Make sure to include the Z in your quote.

To properly parse dates, utilize Gson with this format: new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create();

The significance of the unquoted Z in the SimpleDateFormat used by GsonBuilder can affect time zone interpretation for date strings lacking it.

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

How can Beautiful Soup be used to extract data in JSON format?

I am looking to retrieve data in JSON format instead of the current messy dictionary format. Below is my code snippet: my_dict = {"job_title":[],"time_posted":[],"number_of_proposal":[],"page_link":[]}; for page_num ...

What is the duration of time that broadcast has been in existence?

I have a button on my page. When a user clicks the button, it triggers the following code: as.controller('CustSummary', function($scope, $rootScope, $http, $routeParams, $location) { var loadAbbDetails = function() { ...

Features for React Calculator

I have been developing a React Calculator that includes a display for history and output, along with buttons for numbers and operators. I was successful in rendering the initial structure. For my next task, I aim to update the display with the pressed num ...

Is your website's Google analytics event tracking not giving you the feedback you need

Here's what I'm trying to achieve in the code below: Set up Google Analytics on the page Add a jQuery click event based on specific query strings and domain characters Trigger a Google Analytics tracking event with the click event Implement cod ...

Modifying a value within a loop

var currentmix = document.getElementById('custommix').value.split(","); var additionalcost = 0; for (i = 0; i < currentmix.length; i++) { if (currentmix[i] != "") { var mixinpriceid = "mixinprice"+c ...

Implementing folder-specific routing in Express js

I'm struggling to figure out how to implement a solution that functions like this code snippet. I need to serve different folders based on various parameters, but I'm hitting a roadblock. An example of this in action would be incredibly helpful. ...

`Is it possible to dynamically position my TableLayout and its TableRow elements in specific locations?`

I've encountered some difficulties while setting up my TableRow dynamically with TextViews in TableLayout. I have provided two images - one depicting my current situation and the other showing the mockup of the expected outcome that I am aiming for. I ...

Incorporating new functionality into the current .js file to automatically collapse the navbar when clicking outside

Previously, I utilized .js for my sticky navbar in Bootstrap 4.1.3 and it worked perfectly. However, I attempted to add a function in the script to collapse the navbar on mobile devices when clicking outside the menu, but it wasn't successful. Here i ...

Await that's locked within a solo asynchronous function

async function submitForm(e){ e.preventDefault() console.log(e.target) try { const response = await axios.post('/api/<PATH>', {username, password}); console.log(response.data); const token = response.data.token if (t ...

Exploring the world of lighting and shadows with Three.js

I have a question about the initialization and animation process. When making changes to elements like lights and shadows, I've noticed that using large values during initialization can cause a significant drop in frames per second at the start. So, I ...

Efficient way to implement hover and click features on an SVG map using jQuery

I have a directory map in SVG format containing around 30-40 listings. I have assigned classes to each location within the map. Now comes the challenging part, The objective is to create a tooltip hover effect for each listing that displays the business ...

Issue with displaying record attribute as a text variable

I'm currently attempting to retrieve the attribute odata.type from a record so that I can adjust my EditForm based on its value. Strangely, when I utilize a constant to achieve this and print it with console.log, it appears as follows: ƒ HWType(_ref ...

Integrate openfire with smack for seamless communication

Currently, I am utilizing the Smack API for my Android application and have chosen not to utilize public services. Instead, I have opted to download Openfire. However, I am struggling with establishing a connection between the two platforms. ...

Easily fetching data with AJAX through jQuery

Completely new to using jQuery and AJAX, I attempted the code below for a simple http get request: <html> <head> </head> <body> <script src = "jquery-2.1.4.js"></script> <script src = "app.js"></script& ...

Use jQuery to easily add and remove rows from a table dynamically

Is there a way to dynamically add rows to an HTML table using jQuery by utilizing a popup window? The popup would contain text fields, checkboxes, radio buttons, and an "add" button. Upon clicking the "add" button, a new row would be added to the table. ...

Attempting to insert the symbol "$gt" into a query for a search. {[CastError: Unable to convert value "[object Object]" to date at path "createdAt"]}

In the following code snippet: Reviews.find({createdAt : {"$lt" : app.locals.lastDate}}), I am trying to dynamically change the $lt to $gt. app.post("/scroll", function(req, res){ console.log("req.body...", req.body); var sortCreate = req.body.old ...

Dealing with errors in asynchronous Express: A guide

Scenario: I am currently working on a sizeable project involving the backend of a social media platform. Our tech stack includes MongoDB with Mongoose and Express in JavaScript. One question that arises is whether it is essential to wrap every route in try ...

When Node.js Express processes a query string with pipes, it returns a status code of 400 in the requests

When using Node 12.0.0 and express 4.16.4, I encounter a problem where a request containing the character | (the pipe) always results in a 400 bad request response. Below is a snippet of the server code: var express = require('express'); var a ...

Retrieve the image link from a Flickr JSon Feed

I'm currently displaying images from a flickr feed on my webpage. Everything is working well, but when I click on an image, it takes me to the page where the image is hosted. What I want is for the images to link directly to the image itself, not th ...

Issue: AngularJS Injector Module Error

Recently started learning angularjs and trying to set up an app. Here's a simple and direct way to do it: Angular controller: (function () { 'use strict'; angular .module('myQuotesApp') .controller(' ...