AverageJoe
AverageJoe

Reputation: 63

Java object - how to create objects on the fly

I have an object like the following...its going to be a response object from a Rest API call.

{
    "date": "2020-01-04",
    "oneDayLag": "1.54 ",
    "oneDayLagDayWeight": "1",
    "oneDayLagDate": "2020-01-02",
    "twoDayLag": "1.55 ",
    "twoDayLagDayWeight": "2",
    "twoDayLagDate": "2019-12-31",
    "threeDayLag": "1.54 ",
    "threeDayLagDayWeight": "1",
    "threeDayLagDate": "2019-12-30",
    "fourDayLag": "1.53 ",
    "fourDayLagDayWeight": "3",
    "fourDayLagDate": "2019-12-27",
    "fiveDayLag": "1.52 ",
    "fiveDayLagDayWeight": "1",
    "fiveDayLagDate": "2019-12-26",
    "sixDayLag": "1.52 ",
    "sixDayLagDayWeight": "2",
    "sixDayLagDate": "2019-12-24",
    "sevenDayLag": "1.52 ",
    "sevenDayLagDayWeight": "1",
    "sevenDayLagDate": "2019-12-23",
    "eightDayLag": "1.53 ",
    "eightDayLagDayWeight": "3",
    "eightDayLagDate": "2019-12-20",
    "nineDayLag": "1.53 ",
    "nineDayLagDayWeight": "1",
    "nineDayLagDate": "2019-12-19",
    "tenDayLag": "1.53 ",
    "tenDayLagDayWeight": "1",
    "tenDayLagDate": "2019-12-18"
}

I need to create a reduced/slimmed down version of the object depending on the number of days - for example, if the number of days is '4', then the response object should be the following...

{
    "date": "2020-01-04",
    "oneDayLag": "1.54 ",
    "oneDayLagDayWeight": "1",
    "oneDayLagDate": "2020-01-02",
    "twoDayLag": "1.55 ",
    "twoDayLagDayWeight": "2",
    "twoDayLagDate": "2019-12-31",
    "threeDayLag": "1.54 ",
    "threeDayLagDayWeight": "1",
    "threeDayLagDate": "2019-12-30",
    "fourDayLag": "1.53 ",
    "fourDayLagDayWeight": "3",
    "fourDayLagDate": "2019-12-27"
}

I can write a lot of code (a mix of models, services, if-else etc.) to create such objects between the value of 1 and 10, but is there a more elegant way to approach this problem in Java?

Upvotes: 0

Views: 381

Answers (1)

wikprim
wikprim

Reputation: 26

As holi-java written - use array. Example:

{
  "date": "2020-01-04",
  "lags": [
    {
      "lag": "1.54 ",
      "lagDayWeight":"1",
      "date": "2020-01-02",
      "lagDay": "1"

    },
    {
      "lag": "1.55 ",
      "lagDayWeight":"2",
      "date": "2019-12-31",
      "lagDay": "2"
    }
  ]
}

Upvotes: 1

Related Questions