本文介绍了GSON.如何将json对象转换为json数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我正在从API获取此JSON:

Now I am getting this JSON from API:

{"supplyPrice": {
        "CAD": 78,
        "CHF": 54600.78,
        "USD": 20735.52
      }}

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

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"
    }
  ]
}

如何使用GSON做到这一点?

How to do this using GSON?

推荐答案

感谢Rohit Patil!我根据自己的情况修改了他的代码,它可以正常工作!

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;
}

这篇关于GSON.如何将json对象转换为json数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 07:25