Java 手动解析 JSON 数据到 UserAccountBalance 对象
String json = '{
"arg": {
"channel": "balance_and_position",
"uid": "77982378738415879"
},
"data": [{
"pTime": "1597026383085",
"eventType": "snapshot",
"balData": [{
"ccy": "BTC",
"cashBal": "1",
"uTime": "1597026383085"
}],
"posData": [{
"posId": "1111111111",
"tradeId": "2",
"instId": "BTC-USD-191018",
"instType": "FUTURES",
"mgnMode": "cross",
"posSide": "long",
"pos": "10",
"ccy": "BTC",
"posCcy": "",
"avgPx": "3320",
"uTime": "1597026383085"
}],
"trades": [{
"instId": "BTC-USD-191018",
"tradeId": "2",
}]
}]
}';
UserAccountBalance userAccountBalance = new UserAccountBalance();
JSONObject jsonObject = new JSONObject(json);
JSONArray dataArray = jsonObject.getJSONArray("data");
JSONObject dataObject = dataArray.getJSONObject(0);
JSONArray balDataArray = dataObject.getJSONArray("balData");
JSONObject balDataObject = balDataArray.getJSONObject(0);
userAccountBalance.setBalData(new BigDecimal(balDataObject.getString("cashBal")));
userAccountBalance.setUtime(balDataObject.getString("uTime"));
userAccountBalance.setEventType(dataObject.getString("eventType"));
userAccountBalance.setTradeId(dataObject.getJSONArray("trades").getJSONObject(0).getString("tradeId"));
userAccountBalance.setInstId(dataObject.getJSONArray("trades").getJSONObject(0).getString("instId"));
System.out.println(userAccountBalance);
代码说明:
- 使用
JSONObject和JSONArray对象解析 JSON 数据。 - 从
data数组中获取第一个数据对象。 - 从
balData数组中获取第一个余额数据对象,并将cashBal属性的值设置到userAccountBalance.setBalData()中。 - 从
balData对象中获取uTime属性的值并设置到userAccountBalance.setUtime()中。 - 从
data对象中获取eventType、trades数组中的第一个对象以及instId和tradeId属性的值并分别设置到userAccountBalance对象中。
注意:
- 需要导入
org.json.JSONObject和org.json.JSONArray库。 - 代码示例假设
UserAccountBalance类已定义并具有相应的 setter 方法。 - 可以根据实际需求调整代码逻辑和属性设置。
使用场景:
- 从 JSON 数据中提取特定的数据并将其赋值给 Java 对象。
- 在没有使用 JSON 库的情况下手动解析 JSON 数据。
- 在处理自定义 JSON 格式数据时,可以使用此代码作为参考。
原文地址: http://www.cveoy.top/t/topic/tKB 著作权归作者所有。请勿转载和采集!