Joe Richard Joe Richard - 23 days ago 10
Java Question

GSON. How to convert json object to json array?

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?

Answer

Thanks to Rohit Patil! I modified his code to my situation and it works!

private JSONObject modifyPrices(JSONObject JSONObj) {
    try {
        JSONObject supplyPrice = JSONObj.getJSONObject("supplyPrice");
        JSONArray supplyPriceArray = new JSONArray();
        Iterator<?> keys = supplyPrice.keys();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            String value = supplyPrice.getString(key);
            supplyPriceArray.put(new JSONObject("{\"name\":" + key + ",\"value\":" + value + "}"));
        }
        JSONObj.put("supplyPrice", supplyPriceArray);
        return JSONObj;
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}