How to get the first data object of a data object (REST api)

Advertisements

I Have a REST api that contains the data like this way

{
   ...
   ... //<- more data here
   ...

   "currencies": {
       "BTN": {
          "name": "Bhutanese ngultrum",
          "symbol": "Nu."
       },
       "INR": {
          "name": "Indian rupee",
          "symbol": "₹"
       }
   }

  ...
  ... //<- more data here
  ...
}

i am doing a project in java where i need to use okhttp and show information about a country from an available rest api and before when i used this api it had all the data in currencies in an data array and that was helpful as you can just get the first zero object from the array , but after they updated the api they made all data in currencies an object and i only want the first object , any way i can get it?

>Solution :

OK, so you have two options here …

Option 1.
Create two classes like this and use ObjectMapper class to do automatic deserealisation for you.

class CurrencyData {
  String name;
  String symbol;
}

class CurrencyJsonResponse {
   CurrencyData INR;
   CurrencyData BTN;
}

public static void main(String[] args) {
   OkHttpClient client = // build an instance;
   ObjectMapper objectMapper = new ObjectMapper(); 
   ResponseBody responseBody = client.newCall(request).execute().body(); 
   CurrencyJsonResponse currencyResponse = objectMapper.readValue(responseBody.string(), CurrencyJsonResponse.class);
   //Get data by using getters on currencyResponse object
}

Option 2
You can write a custom deserealizer by extending the StdDeserializer<T> class. You’ll have to programmatically inspect the JsonNode parse tree and assemble the object that you want.

This article explains how to do it and comes with a working code sample

Leave a ReplyCancel reply