Home > Enterprise >  How to map a JSON response to java class object
How to map a JSON response to java class object

Time:08-03

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, unique = true)
    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.

CodePudding user response:

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());

CodePudding user response:

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

  • Related