【问题标题】:GSON. How to convert json object to json array?GSON。如何将json对象转换为json数组?
【发布时间】:2016-05-07 03:13:34
【问题描述】:

现在我从 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 做到这一点?

【问题讨论】:

  • 如果我正确理解您的问题,您可能会收到 JsonObject 或 JsonArray。您可以调用 getAsJsonObject() 方法,如果失败,请调用 getAsJsonArray()。
  • 或者使用isJsonObject()方法,根据结果调用getAsJsonObject()或者getAsJsonArray()。

标签: java android json parsing gson


【解决方案1】:

您可以直接将其转换为HashMap or TreeMap,然后浏览您的地图以查找所有键。

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

【讨论】:

    【解决方案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】:

      希望这部分代码对你有所帮助:

          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());
      

      【讨论】:

        【解决方案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(String pJson, Class pClassType) 转换成JAVA对象了

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

        现在可以使用arraylist来获取数据了。

        【讨论】:

          【解决方案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】:

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

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

            【讨论】:

              【解决方案7】:

              我们只需要一行代码就可以将 jsonObjects 转换为数组(不是 jsonArrays,但在将其设为 arrayList 后,您也可以轻松创建 jsonArray。)

              fun <LIST_TYPE>jsonObjectToArray(jsonObject : JsonObject,listTypeClass : Class<LIST_TYPE>) = arrayListOf<LIST_TYPE>().apply { jsonObject.keySet().forEach { this.add(Gson().fromJson(jsonObject.get(it).toString(),listTypeClass))}}
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2012-02-29
                • 2016-08-07
                • 1970-01-01
                • 2015-09-13
                • 1970-01-01
                • 2016-02-15
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多