GSON.如何将json对象转换为json数组?

Joe*_*ard 6 java parsing android json gson

现在我从API获取这个JSON:

{"supplyPrice": {
        "CAD": 78,
        "CHF": 54600.78,
        "USD": 20735.52
      }}
Run Code Online (Sandbox Code Playgroud)

但价格是动态的,这就是为什么我需要这种形式的JSON

{
  "supplyPrice": [
    {
      "name": "CAD",
      "value": "78"
    },
    {
      "name": "TRY",
      "value": "34961.94"
    },
    {
      "name": "CHF",
      "value": "54600.78"
    },
    {
      "name": "USD",
      "value": "20735.52"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

如何使用GSON做到这一点?

Joe*_*ard 1

感谢罗希特·佩蒂尔!我根据我的情况修改了他的代码并且它有效!

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;
}
Run Code Online (Sandbox Code Playgroud)