Now I am getting this JSON from API:
{"supplyPrice": {
"CAD": 78,
"CHF": 54600.78,
"USD": 20735.52
}}
But prices are dynamic, that's why I need JSON in this form
{
"supplyPrice": [
{
"name": "CAD",
"value": "78"
},
{
"name": "TRY",
"value": "34961.94"
},
{
"name": "CHF",
"value": "54600.78"
},
{
"name": "USD",
"value": "20735.52"
}
]
}
How to do this using GSON?
There are two parameters in the fromJson() method, the first parameter is JSON String which we want to parse and the second parameter is Java class to parse JSON string. We can pass one parameter into the toJson() method is the Java object which we want to convert into a JSON string.
The GSON JsonParser class can parse a JSON string or stream into a tree structure of Java objects. GSON also has two other parsers. The Gson JSON parser which can parse JSON into Java objects, and the JsonReader which can parse a JSON string or stream into tokens (a pull parser).
Gson is the main actor class of Google Gson library. It provides functionalities to convert Java objects to matching JSON constructs and vice versa. Gson is first constructed using GsonBuilder and then toJson(Object) or fromJson(String, Class) methods are used to read/write JSON constructs.
GSON uses POJO classes to parse JSON into java objects.
Create A java class containing variables with names and datatype same as keys of JSON object. I think the JSON you are getting is not in the right format.
Class SupplyPrice{
double CAD;
double CHF;
double TRY
}
Class SupplyPriceContainer{
ArrayList<SupplyPrice> supplyPrice;
}
And your JSON should be
{
"CAD": 78,
"CHF": 54600.78,
"USD": 20735.52
}
{
"supplyPrice": [{
"CAD": 78,
"CHF": 0,
"USD": 0
}, {
"CAD": 0,
"CHF": 54600.00,
"USD": 0
}, {
"CAD": 0,
"CHF": 0,
"USD": 20735.52
}]
}
Then you can Use GSON's `fromJson(String pJson, Class pClassType) to convert to JAVA object
Gson gson = new Gson()
ArrayList<SupplyPrice> suplyPrices = gson.fromJson(pJsonString, SupplyPrice.class);
Now you can use the arraylist to get the data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With