0

I am using Java Spring Boot. What approach should I take to map my JSON response to my class?

I'm looking to write a method that will go over the JSON and create ShareDataDaily objects from the entries that are under "Time Series (Daily)". The date is a key of the object and the price that I want to use is the "4. open".

I plan to make a list of these objects that will be saved into my database.

Any help appreciated.

JSON

{
   "Meta Data":{
      "1. Information":"Daily Prices (open, high, low, close) and Volumes",
      "2. Symbol":"MSFT",
      "3. Last Refreshed":"2022-08-01",
      "4. Output Size":"Compact",
      "5. Time Zone":"US/Eastern"
   },
   "Time Series (Daily)":{
      "2022-08-01":{
         "1. open":"277.8200",
         "2. high":"281.2800",
         "3. low":"275.8400",
         "4. close":"278.0100",
         "5. volume":"21539580"
      },
      "2022-07-29":{
         "1. open":"277.7000",
         "2. high":"282.0000",
         "3. low":"276.6300",
         "4. close":"280.7400",
         "5. volume":"32152752"
      },
      "2022-07-28":{
         "1. open":"269.7500",
         "2. high":"277.8400",
         "3. low":"267.8700",
         "4. close":"276.4100",
         "5. volume":"33459327"
      },
      "2022-07-27":{
         "1. open":"261.1600",
         "2. high":"270.0500",
         "3. low":"258.8500",
         "4. close":"268.7400",
         "5. volume":"45994049"
      }
   }
}

Class

package com.example.demo.shareDataDaily;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import javax.persistence.*;


@Entity
@Table
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor

public class ShareDataDaily {

    @Id
    @SequenceGenerator(
            name = "sharedatadaily_sequence",
            sequenceName = "sharedatadaily_sequence",
            allocationSize = 1
    )
    @GeneratedValue(
            strategy = GenerationType.SEQUENCE,
            generator = "sharedatadaily_sequence"
    )
    private Long id;
    @Column(nullable = false)
    private String symbol;
    @Column(nullable = false)
    private String date;
    @Column
    private Double openPrice;

    public ShareDataDaily(String symbol, String date, Double openPrice) {
        this.symbol = symbol;
        this.date = date;
        this.openPrice = openPrice;
    }
}

Method to get the JSON from external API

public List<ShareDataDaily> getShareDataDaily(String symbol) throws JSONException {

        WebClientToGetShareItemProperties properties = new WebClientToGetShareItemProperties();
        properties.setBaseUrl(WebClientUrlEnum.BASE_URL.getUrl());
        properties.setEndPoint(WebClientUrlEnum.DAILY_DATA.getUrl());

        WebClientToGetAPI webClientToGetAPI = new WebClientToGetAPI(WebClient.create(), properties);

        String dailyDataObj = webClientToGetAPI.getShareInfoFromApiBySymbol(symbol);

        JSONObject dailyDataJsonObj = new JSONObject(dailyDataObj);
        
        
        return listOfData;
    }

As you can see I have gotten to the stage where I have the JSON available to be worked with but I cannot figure out what approach to take here to be able to map each of the "Time Series (Daily)" nested objects into a ShareDataDaily class objects so that it can be saved into the DB.

2 Answers 2

1
String dailyDataObj = "{\"MetaData\":{\"1.Information\":\"DailyPrices(open,high,low,close)andVolumes\",\"2.Symbol\":\"MSFT\",\"3.LastRefreshed\":\"2022-08-01\",\"4.OutputSize\":\"Compact\",\"5.TimeZone\":\"US/Eastern\"},\"TimeSeries(Daily)\":{\"2022-08-01\":{\"1.open\":\"277.8200\",\"2.high\":\"281.2800\",\"3.low\":\"275.8400\",\"4.close\":\"278.0100\",\"5.volume\":\"21539580\"},\"2022-07-29\":{\"1.open\":\"277.7000\",\"2.high\":\"282.0000\",\"3.low\":\"276.6300\",\"4.close\":\"280.7400\",\"5.volume\":\"32152752\"},\"2022-07-28\":{\"1.open\":\"269.7500\",\"2.high\":\"277.8400\",\"3.low\":\"267.8700\",\"4.close\":\"276.4100\",\"5.volume\":\"33459327\"},\"2022-07-27\":{\"1.open\":\"261.1600\",\"2.high\":\"270.0500\",\"3.low\":\"258.8500\",\"4.close\":\"268.7400\",\"5.volume\":\"45994049\"}}}";

Considering you are getting above String as json object. Please follow below code for desire output.

    org.json.JSONObject dailyDataJsonObj = new org.json.JSONObject(dailyDataObj);

    List< ShareDataDaily> list =new ArrayList<>();

    String symbol = (String) dailyDataJsonObj.getJSONObject("MetaData").get("2.Symbol");

    org.json.JSONObject timeSeries = (org.json.JSONObject) dailyDataJsonObj.get("TimeSeries(Daily)");

    Set<String> times = timeSeries.keySet();
    for(String time : times){
        Model model  = new Model();
        model.setDate(time);
        model.setSymbol(symbol);
        model.setOpenPrice(Double.parseDouble((String) timeSeries.getJSONObject(time).get("1.open")));
        list.add(model);
     
    }

Don't forget to confirm if this worked. Thanks

Sign up to request clarification or add additional context in comments.

1 Comment

pay attention to differences in the json between original question and this answer.
0

here is what you could do using Java Stream API:

    final JSONObject dailyDataJsonObj = new JSONObject(dailyDataObj);
    final String symbol = dailyDataJsonObj.getJSONObject("Meta Data").getString("2. Symbol");
    final JSONObject timeSeriesDailyJsonObj = dailyDataJsonObj.getJSONObject("Time Series (Daily)");

    final List<ShareDataDaily> listOfData = timeSeriesDailyJsonObj.keySet().stream()
        .map(date -> new ShareDataDaily(symbol, date, timeSeriesDailyJsonObj.getJSONObject(date).getDouble("1. open")))
        .collect(Collectors.toList());

2 Comments

It worked. Thanks a lot. I ran into one problem with your solution. I was importing the wrong JSONObject dependency and because of that keySet() method could not be resolved but I have figured that part out now and it works just as I wanted it to.
you probably speak about org.json VS org.json.simple :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.