问题描述
我有 JSONObject
,其中包含如下所示并创建的类 Markets 包含所有字段。我想将 JSONObject
元素放置到 Markets
的创建对象中。例如: Markets markets = new Markets()
,然后把元素放到 JSONObject
到 markets
,我希望能够获得 markets.getInstrumentName()
。我怎么做到这一点?
我尝试使用 Gson
,像这样 Markets markets = gson2.fromJson(jsonObject,Markets.class);
但是有不同的类型,这是错误的方法。
JSONObject
{
map:{
netChange :-81.0,
instrumentType:INDICES,
percentageChange:-1.31,
scalingFactor:1,
epic:IX.D. FTSE.DAILY.IP,
updateTime:00:02:48,
updateTimeUTC:23:02:48,
offer:6095.8,
instrumentName:FTSE 100,
高:6188.3,
低:6080.8,
streamingPricesAvailable:true,
marketStatus: 可交易,
delayTime:0,
过期:DFB,
出价:6094.8
}
}
Markets
:
class Markets {
private double bid;
私人双人优惠;
private int delayTime;
private String史诗;
私人字符串到期;
私人双高;
私人双低;
private String instrumentName;
private String instrumentType;
私人字符串marketStatus;
private double netChange;
private double percentageChange;
private int scalingFactor;
私有布尔streamingPricesAvailable;
私人字符串updateTime;
私人字符串updateTimeUTC;
// getters and setters
}
JSONObject jsonObject = // ...
ObjectMapper mapper = new ObjectMapper();
Markets markets = mapper.readValue(jsonObject.toString(),Markets.class);
I have JSONObject
which contains as shown below and created class Markets
contained all fields. I want put JSONObject
elements to created object of Markets
.
Example: Markets markets = new Markets()
,then put elements from JSONObject
to markets
and I want to be able to get markets.getInstrumentName()
. How can I do this ?
I try using Gson
, like this Markets markets = gson2.fromJson(jsonObject, Markets.class);
but there are different types and it is wrong way.
JSONObject
:
{
"map": {
"netChange": -81.0,
"instrumentType": "INDICES",
"percentageChange": -1.31,
"scalingFactor": 1,
"epic": "IX.D.FTSE.DAILY.IP",
"updateTime": "00:02:48",
"updateTimeUTC": "23:02:48",
"offer": 6095.8,
"instrumentName": "FTSE 100",
"high": 6188.3,
"low": 6080.8,
"streamingPricesAvailable": true,
"marketStatus": "TRADEABLE",
"delayTime": 0,
"expiry": "DFB",
"bid": 6094.8
}
}
Markets
:
class Markets {
private double bid;
private double offer;
private int delayTime;
private String epic;
private String expiry;
private double high;
private double low;
private String instrumentName;
private String instrumentType;
private String marketStatus;
private double netChange;
private double percentageChange;
private int scalingFactor;
private boolean streamingPricesAvailable;
private String updateTime;
private String updateTimeUTC;
//getters and setters
}
Using Jackson library
JSONObject jsonObject = //...
ObjectMapper mapper = new ObjectMapper();
Markets markets = mapper.readValue(jsonObject.toString(), Markets.class);
这篇关于来自JSONObject的指定对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!