I'm working on a project at the moment that requires me to take in a various currency pairs and generate a response object from an API call response. I'm using jackson to map the JSON response to java objects then reading data from an ArrayList generated. The problem is the JSON response can have the different currency pairing strings as a key for the list of pairing data. Here's what a typical response looks like:
{"error":[],"result":{"XXBTZUSD":[[1647062100,"39091.2","39184.9","39088.9","39139.0","39150.9","59.22447291",161],}[1647063000,"39138.9","39188.4","39138.9","39151.2","39174.2","2.92905848",126]]}
The problem arises when I try to pull data from a different currency pair as my result object is hard coded to pull the data for the JSON key XXBTZUSD. Here's what my result object looks like:
public class Result{
@JsonProperty("XXBTZUSD")
public ArrayList<ArrayList<Object>> candles;
public int last;
}
I was thinking having the @JsonProperty be variable and pass in the key from the json response to correct pull the currnecy pair I set it to, but JsonProperty needs to be a constant. The only way around this I can see is to have a ton of different classes for each currency pair but that would be inefficient and take around 15 separate classes to do. I'm not too familiar with the jackson library. If anyone has any ideas of how to solve this I would be greatly appreciative, I've been trying to figure out a way around this for awhile now. Thank you!
CodePudding user response:
If keys can be different, one option is to use a Map
. Your Result
class won't be needed, parse the result property into Map<String, Object>
. Then extract like this:
Map<String, Object> result = deserialize();
ArrayList<ArrayList<Object>> arrays = (ArrayList<ArrayList<Object>>) result.get("XXBTZUSD");
Just change property depending on which currency pair you need.
Another option is writing custom deserializer, in which to always put value in your candles
field, regardless of how the property is named in json.