来自JSONObject

时间:2016-04-01 11:11:49

标签: java json gson

我有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",
    "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
}

2 个答案:

答案 0 :(得分:3)

使用杰克逊图书馆

JSONObject jsonObject = //...
ObjectMapper mapper = new ObjectMapper();
Markets markets = mapper.readValue(jsonObject.toString(), Markets.class);

答案 1 :(得分:2)

当您要将JSON转换为对象时,以下是示例代码:

yourObject = new Gson().fromJson(yourJSONObject.toString(), YourObject.class);

我正在使用Gson 2.4。它工作正常。

compile 'com.google.code.gson:gson:2.4'