首页 > 解决方案 > 在 Java 中使用 JSON 创建对象

问题描述

使用 API,我需要一个包含大量不同数据的选项链。它看起来像这样:

```
[
  putCall=PUT
  symbol=AAPL_012023P100
  description=AAPL Jan 20 2023 100 Put
  exchangeName=OPR
  bidPrice=10.05
  askPrice=10.3
  lastPrice=10.15
  bidAskSize=78X102
  markPrice=10.18
  bidSize=78
  askSize=102
  lastSize=0
  highPrice=10.15
  lowPrice=9.85
  openPrice=0.0
  closePrice=9.98
  totalVolume=334
  quoteTimeInLong=1612904400035
  tradeTimeInLong=1612903831902
  netChange=0.17
  volatility=37.645
  delta=-0.195
  gamma=0.004
  theta=-0.014
  vega=0.524
  rho=-0.676
  timeValue=10.15
  openInterest=7941
  isInTheMoney=false
  theoreticalOptionValue=10.175
  theoreticalVolatility=29.0
  isMini=false
  isNonStandard=false
  optionDeliverablesList=<null>
  strikePrice=100.0
  expirationDate=1674248400000
  expirationType=R
  multiplier=100.0
  settlementType= 
  deliverableNote=
  isIndexOption=<null>
  percentChange=1.75
  markChange=0.2
  markPercentChange=2.01
  otherFields={lastTradingDay=1674262800000, daysToExpiration=709, tradeDate=null}
]], ```

这是它返回的众多产品中的一部分。我需要所有这些。因此,使用 Jackson,我了解如何使用以下方式将其转换为 JSON:

```
    ObjectMapper mapper = new ObjectMapper();
    String data = eq.toString();
    mapper.writerWithDefaultPrettyPrinter().writeValueAsString(data); 

现在,这清理了一些,但现在我真正需要的是......我需要这一切中的三件事。我想使用以下字段为这些事物中的每一个创建一个对象:openInterest、totalVolume 和描述。

我试过搜索这个,但是当你有多个值时我无法弄清楚。我在上面发布的只是 API 返回给我的众多条目之一。我真的很感激一些帮助:)

标签: javajsonjackson

解决方案


这个:

[
  putCall=PUT
  symbol=AAPL_012023P100

  /*bla di bla whatever*/

  markPercentChange=2.01
  otherFields={lastTradingDay=1674262800000, daysToExpiration=709, tradeDate=null}
]], ``

我叫这个leSRC

  JSONObject zTHING = new JSONObject();

  zTHING.put("openInterest", leSRC.getJSONObject("openInterest"));
  zTHING.put("totalVolume",  leSRC.getJSONObject("totalVolume"));
  zTHING.put("description",  leSRC.getJSONObject("description"));

您的zTHING对象应该正确设置了这 3 个 KvP。


推荐阅读