使用 Gson 反序列化为不同的 POJO 类型

问题描述 投票:0回答:0

我有 Websocket API,它以 JSON 格式输出数据,客户端端点对它们做出异步反应。 由于 Jsons 很长,我想以反序列化的形式使用它们。 Gson 可以将 JSON 反序列化为 POJO 对象。但是,如果不同的传入 JSON 具有完全不同的结构怎么办?

例如2个通道响应如下:

“符号”频道

{
    "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
       }
     }
    ]
}

“书”频道

{
  "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
  }]
}

最明显的方法是尝试将 JSON 反序列化到每个 POJO 类中,并在 POJO 类不正确时捕获 JsonSyntaxException。

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) {
    }
}

然而,这看起来有点丑陋且不理想。

java gson pojo
© www.soinside.com 2019 - 2024. All rights reserved.