有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaGSON。如何将json对象转换为json数组?

现在,我从API获得了这个JSON:

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

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

{
  "supplyPrice": [
    {
      "name": "CAD",
      "value": "78"
    },
    {
      "name": "TRY",
      "value": "34961.94"
    },
    {
      "name": "CHF",
      "value": "54600.78"
    },
    {
      "name": "USD",
      "value": "20735.52"
    }
  ]
}

如何使用GSON实现这一点


共 (6) 个答案

  1. # 1 楼答案

    希望这部分代码能够帮助您:

        String json = "{\"supplyPrice\": {\n" +
                "        \"CAD\": 78,\n" +
                "        \"CHF\": 54600.78,\n" +
                "        \"USD\": 20735.52\n" +
                "      }}";
    
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(json, JsonObject.class);
        JsonObject supplyPrice = jsonObject.get("supplyPrice").getAsJsonObject();
        Type type = new TypeToken<HashMap<String, Double>>() {
        }.getType();
        HashMap<String, Double> parsedJson = gson.fromJson(supplyPrice, type);
        JsonArray jsonArray = new JsonArray();
        for(String key : parsedJson.keySet()) {
            JsonObject jo = new JsonObject();
            jo.addProperty("name", key);
            jo.addProperty("value", parsedJson.get(key));
            jsonArray.add(jo);
        }
        JsonObject result = new JsonObject();
        result.add("supplyPrice", jsonArray.getAsJsonArray());
    
  2. # 2 楼答案

    您需要迭代supplyPrice对象的所有键,并使用该键值创建新的JSONArray,然后将新数组分配给supplyPrice键

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

    然后在需要的地方调用函数

    try {
            JSONObject JSONObj = new JSONObject("{'taxes': [],'name': 'Laboriosam iusto eum','requiresShipping': false,  'taxable': true,  'sku': 'QBA84J18832',  'product': 12, 'supplyPrice': {    'CAD': 78,   'CHF': 54600.78,    'USD': 20735.52  }}");
            JSONObj = changeSupplyPrice(JSONObj);
            Log.e("Return JSON Object",JSONObj.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    
  3. # 3 楼答案

    您可以直接将其转换为HashMap or TreeMap,然后在地图中导航所有键

    这将是实现你想要的最简单的方法

  4. # 4 楼答案

    GSON使用POJO类将JSON解析为java对象

    创建一个java类,其中包含名称和数据类型与JSON对象键相同的变量。我认为您得到的JSON格式不正确

    Class SupplyPrice{
     double CAD;
     double CHF;
     double TRY
    }
    
    Class SupplyPriceContainer{
     ArrayList<SupplyPrice> supplyPrice;
    }
    

    您的JSON应该是

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

    然后可以使用GSON的`fromJson(字符串pJson,类pClassType)转换为JAVA对象

      Gson gson = new Gson()
      ArrayList<SupplyPrice> suplyPrices = gson.fromJson(pJsonString, SupplyPrice.class);
    

    现在可以使用arraylist获取数据

  5. # 5 楼答案

    看看这个。。我可以帮你

     JSONObject json= json.getJSONObject("supplyPrice");
        Iterator i = json.keys();
        JSONArray jsonArray = new JSONArray();
    
        while (i.hasNext()){
            String key = (String) i.next();
            jsonArray.put(json.get(key));
    
  6. # 6 楼答案

    多亏了罗希特·帕蒂尔!我根据我的情况修改了他的代码,结果成功了

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