I have Websocket API, which spews out data in JSON format, and client endpoint reacts on them asynchronously. Since Jsons are lengthy, I want to work with them in deserialized form. Gson can deserialize JSON to POJO objects. But what to do, if different incoming JSONs have totally different structure?
For example, 2 channels respond in the following manner:
"symbols" channel
{
"channel": "symbols",
"action": "snapshot",
"data": [
{
"symbol": "BTC_USDT",
"baseCurrencyName": "BTC",
"quoteCurrencyName": "USDT",
"displayName": "BTC/USDT",
"state": "NORMAL",
"visibleStartTime": 1234567890,
"tradableStartTime": 1234567890,
"symbolTradeLimit": {
"symbol": "BTC_USDT",
"priceScale": 10,
"quantityScale": 8,
"amountScale": 8,
"minQuantity": "0.000000000000000001",
"minAmount": "0.000000000000000001",
"highestBid": "0.00",
"lowestAsk": "0.00"
},
"crossMargin": {
"supportCrossMargin": true,
"maxLeverage": 3
}
}
]
}
"book" channel
{
"channel": "book",
"data": [{
"symbol": "BTC_USDT",
"createTime": 1648052239156,
"asks": [],
"bids": [
["40001.5", "2.87"],
["39999.4", "1"]
],
"id": 123456,
"ts": 1648052239192
},
…
{
"symbol": "BTC_USDT",
"createTime": 1648052239156,
"asks": [],
"bids": [
["40001", "2.87"],
["39999", "1"]
],
"id": 345678,
"ts": 1648052239192
}]
}
The most obvious way is trying to deserialize JSON into each POJO class and catch JsonSyntaxException when POJO class is not correct.
public void handleMessage(String message) {
SymbolsResponse symbolsResponse;
BookResponse bookResponse;
try {
bookResponse = gson.fromJson(message, BookResponse.class);
if (bookResponse != null &&
bookResponse.getChannel().equals("book") &&
bookResponse.getData().get(0).getAsks().size() > 0) {
// Here is handling logic for first message type
}
} catch (NullPointerException | JsonSyntaxException ignoredException) {
}
try {
symbolsResponse = gson.fromJson(message, SymbolsResponse.class);
if (symbolsResponse.getChannel().equals("symbols") &&
symbolsResponse.getData() != null) {
// Here is handling logic for second message type
}
} catch (NullPointerException | JsonSyntaxException ignoredException) {
}
}
However, this looks somehow ugly and non-optimal.