GSON. How to convert json object to json array?

前端 未结 7 1878
没有蜡笔的小新
没有蜡笔的小新 2021-02-08 15:20

Now I am getting this JSON from API:

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

But

7条回答
  •  失恋的感觉
    2021-02-08 16:03

    You need to iterate all keys of supplyPrice object, and create New JSONArray using that key value then assign new array to supplyPrice key

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

    then call the function where you want

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

提交回复
热议问题