How to access the name of a JSON object?

bugra.anadol :

I have this JSON returned me from Firebase Realtime Database.

{
       "betslipid-4322": {
            "amount": 100,
            "bets": [
                {
                    "betType": "FT_RESULT_0",
                    "matchid": "ts-fb",
                    "odd": 2.4,
                    "status": "WAITING"
                }
            ],
            "status": "WAITING"
        },
        "betslipid-4323": {
            "amount": 7.5,
            "bets": [
                {
                    "betType": "FT_RESULT_2",
                    "matchid": "gs-fb",
                    "odd": 2.7,
                    "status": "WAITING"
                },
                {
                    "betType": "FT_RESULT_1",
                    "matchid": "gs-gb",
                    "odd": 1.3,
                    "status": "WAITING"
                }
            ],
            "status": "WAITING"
        }
}

I want to place the attributes of this JSON (including the betSlipID at the beginning) to the following Java class.

public class BetSlip {

    private List<Bet> bets;

    private Float amount;

    private BetStatus status;

    private betSlipID;
}

However, I was unable to access the betSlipIDs which are "betslipid-4322" and "betslipid-4323" in this case and I was also unable to convert the JSON to my java class by the following code.

private RestTemplate restTemplate = new RestTemplate();
List<BetSlip> betSlip = restTemplate.getForObject(getDatabaseLink("incomplete-betslips"), ArrayList.class);

Note that I don't know the betSlipIDs when I get the JSON response, so I can't create another class which includes a variable named the incoming betSlipID.

user404 :

I am not saying this is optimal, but you can follow this to do your task as your betslipid-x is variable, I am describing the steps to be followed only:

  1. just return a json object from your restTemplate see Spring restTemplate get raw json string
  2. get the keys applying keySet() on your returned json and you will get all your betslipid-x
  3. based on that, get associated object of that key and deserialize in your BetSlip class and set the key as betSlipID.
  4. Thus you get your desired object.

This should do your job.
Let me know if your need further clarification.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=20895&siteId=1