1

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: []
user9347049
  • 1,927
  • 3
  • 27
  • 66
  • A `for` loop in Java uses semi-colon character as delimiter, not comma. – Basil Bourque Feb 26 '21 at 16:31
  • 2
    Never use `Calendar`, part of the terrible date-time classes that were years ago supplanted by the modern *java.time* classes defined in JSR 310. – Basil Bourque Feb 26 '21 at 16:32
  • @BasilBourque Well I am very new to this... how should I use it then? Any code advice appreciated :) – user9347049 Feb 26 '21 at 16:33
  • Yes I did modify it a bit since posting question. But small changes. So I would like for each hour of the day that data from my JSON is showed. Do you maybe have any idea how can I do it? – user9347049 Feb 26 '21 at 19:22
  • Hi @OleV.V. I updated my question I hope this time it will work. I am here for questions. Thank you. – user9347049 Feb 26 '21 at 19:45

2 Answers2

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.

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.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
1

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();
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • @user9347049 `StringBuilder` is already used nicely in the other answer, so I have added but a small supplement in mine. Your search engine will find numerous other code examples. – Ole V.V. Feb 26 '21 at 21:00