CeZet
CeZet

Reputation: 1513

Specified object from JSONObject

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
}

Upvotes: 1

Views: 94

Answers (2)

Gujarat Santana
Gujarat Santana

Reputation: 10564

Here is sample Code when you want to convert JSON to object :

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

I'm using Gson 2.4. and it works fine.

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

Upvotes: 1

user5789865
user5789865

Reputation:

Using Jackson library

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

Upvotes: 3

Related Questions