How to display JSON list for each hour of day - Java, SpringBoot

103
February 27, 2021, at 3:20 PM

I am mapping JSON data to object model in SpringBoot, looping through it and displaying it in the console.

What I am trying to do next is display JSON data FOR EACH HOUR OF THE DAY.

I googled trough what's online like this existing question but unfortunately I was not able to apply it.

Run Java code once every hour - Stackoverflow

Any suggestion would be appreciated.

I started with something like this in my model class.

public class CarResponse {
    List<Car> car = new ArrayList<Car>();
    public List<Car> getCar() {
        return car;
    }
    public void setCar(List<Car> car) {
        this.car = car;
    }
    @Override
    public String toString() {
        final DateFormat df = DateFormat.getDateTimeInstance();
        final Calendar c = Calendar.getInstance();
        c.clear();
        for (c.add(Calendar.HOUR_OF_DAY, 1)) {
            System.out.println(df.format(c.getTime()));
            String str = "=================================\r\n";
            for (Car ld : car) {
                str += "\t" + "Shop: " + ld.getShop() + "\r\n";
                str += "\t" + "Date: " + ld.getDate() + "\r\n";
                str += "\t" + "Values: " + ld.getValues() + "\r\n";
            }
            return str;
        }
    }
}

With code above I didn't get what I wanted. Well to explain better I don't have an error, but I would like my data to be displayed in the console like this:

2021-02-26T00:00+01:00[Europe/Vienna]
=================================
    Market: Audi
    Date: 12321599600000
    Values: []
=================================
2021-02-26T00:00+02:00[Europe/Vienna]
    Market: Audi
    Date: 12321599600000
    Values: []

Right now I get the output like this:

2021-02-26T00:00+01:00[Europe/Vienna]
2021-02-26T00:00+01:00[Europe/Vienna]
    =================================
        Market: Audi
        Date: 12321599600000
        Values: []
        Market: Audi
        Date: 12321599600000
        Values: []
Answer 1

The java.util date-time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.

  • For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7.
  • If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Also, I recommend you use StringBuilder instead of String for such a case because repeated string concatenation in a loop creates additional as many instances of String as the number of concatenation. Check this discussion to learn more about it.

Demo:

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
class Main {
    public static void main(String[] args) {
        // Start of the day
        ZonedDateTime zdt = LocalDate.now().atStartOfDay(ZoneId.systemDefault());
        StringBuilder sb = new StringBuilder();
        sb.append(zdt.toString()).append(System.lineSeparator());
        for (int i = 1; i <= 23; i++) {
            zdt = zdt.plusHours(1);
            sb.append(zdt.toString()).append(System.lineSeparator());
        }
        System.out.println(sb);
    }
}

Output:

2021-02-26T00:00Z[Europe/London]
2021-02-26T01:00Z[Europe/London]
2021-02-26T02:00Z[Europe/London]
...
...
...
2021-02-26T22:00Z[Europe/London]
2021-02-26T23:00Z[Europe/London]

Learn more about the modern date-time API from Trail: Date Time.

Answer 2

I believe that your problem (apart from using the poorly designed and long outdated date classes as explained in the other answer) is the return statement inside your outer for loop.

This statement causes your toString method to exit:

        return str;

Only the string built up through the first time through the outer for loop is returned. The subsequent expected iterations of the loop never even happen.

Instead you need to declare str outside (that is, before) the first for loop. And only return it after that loop has ended, run to completion.

You may also consider using a StringBuffer or StringBuilder, but that’s a different story. Edit: There is already an example of using StringBuilder in the other answer. As you can see there, you may chain calls to its append method:

        sb.append(zdt.toString()).append(System.lineSeparator());

In your case you may want to use a longer chain, for example something like:

        sb.append("\t").append("Shop: ").append(ld.getShop()).append("\r\n")
            .append("\t").append("Date: ").append(ld.getDate()).append("\r\n")
            .append("\t").append("Values: ").append(ld.getValues()).append("\r\n");

Your toString method must return a String. Just use the StingBuilder’s toString method for that:

    return sb.toString();
READ ALSO
Use Anaconda environment in Atom (Mac OS)

Use Anaconda environment in Atom (Mac OS)

I am working on Mac OS and installed AtomI was wondering if there's a way to make all the packages from my anaconda3 environment available in Atom

105
Get column type from schema in Laravel 8

Get column type from schema in Laravel 8

I'm getting some columns from various tables within my project and would look to obtain some additional information other than the column name, I'd like to get the column type as well

143
Javascript Sprite Animation Not Transparent

Javascript Sprite Animation Not Transparent

New to javaScript as a language but a fair amount of programming and developer experience

109
Remove WooCommerce Tags when print invoice

Remove WooCommerce Tags when print invoice

I have a wordpress websiteI have been facing a problem with the website

48