GSON. How to convert json object to json array?

前端 未结 7 1867
没有蜡笔的小新
没有蜡笔的小新 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 15:59

    We are only one line of code away from converting jsonObjects to arrays(Not jsonArrays but after making it a arrayList you can create jsonArray too,easily.)

    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))}}
    
    0 讨论(0)
  • 2021-02-08 16:00

    Once look at this.. may help you.

     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));
    
    0 讨论(0)
  • 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();
        }
    
    0 讨论(0)
  • 2021-02-08 16:03

    You can directly convert it to an HashMap or TreeMap then navigate your map for all the keys.

    This will be simplest way to achieve what you want.

    0 讨论(0)
  • 2021-02-08 16:04

    GSON uses POJO classes to parse JSON into java objects.

    Create A java class containing variables with names and datatype same as keys of JSON object. I think the JSON you are getting is not in the right format.

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

    And your JSON should be

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

    Then you can Use GSON's `fromJson(String pJson, Class pClassType) to convert to JAVA object

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

    Now you can use the arraylist to get the data.

    0 讨论(0)
  • 2021-02-08 16:14

    Hope this part of code to help you:

        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());
    
    0 讨论(0)
提交回复
热议问题