将JsonObject存储到HasMap中

时间:2018-03-29 09:52:54

标签: java android android-json gson

我低于jsonResponse。

在每个回复中,键和值都会发生变化。

我想存储计数& previousCountDay HashMap 中的键和值。

Json回复:

{
    "count": {
        "2018-03-28 18": 55,
        "2018-03-28 19": 48,
        "2018-03-28 20": 41,
        "2018-03-28 21": 31,
        "2018-03-28 22": 32,
        "2018-03-28 23": 26,
        "2018-03-29 00": 20,
        "2018-03-29 01": 16,
        "2018-03-29 02": 12,
        "2018-03-29 03": 0
    },
    "previousCountDay": {
        "2018-03-27 18": 40,
        "2018-03-27 19": 59,
        "2018-03-27 20": 53,
        "2018-03-27 21": 48,
        "2018-03-27 22": 36,
        "2018-03-27 23": 40,
        "2018-03-28 00": 37,
        "2018-03-28 01": 14,
        "2018-03-28 02": 29,
        "2018-03-28 03": 1
    }, 
    "noOfIntervals": 10,
    "range": [
        "18",
        "19",
        "20",
        "21",
        "22",
        "23",
        "00",
        "01",
        "02",
        "03"
    ]
}

通过使用GSON我得到JSON响应,但我只存储range,因为它来自JSON数组,range我的大小为count& previousCountDay

以下是活动类:

 private void JsonRequestOrderVelocity(String dmhw) {
    utils.showDialog();

    String url = Constants.VELOCITY_API;
    Log.e("URL", "" + url);

    JsonObjectRequest request = new JsonObjectRequest(url, null,
            response -> {
                Log.e("onResponse",""+response);
                try {
                    Gson gson = new Gson();
                    Type listType = new TypeToken<OrderVelocityPojo>() {
                    }.getType();

                    orderVelocityPojo = gson.fromJson(response.toString(), listType);

                    Log.e("SIZE",""+orderVelocityPojo.getRange().size());

                    JSONObject object = response.getJSONObject("count");

                    Map<String, Integer> countMap = new HashMap<String, Integer>();

                    //store keys and values in HashMap.
                    for(int i=0;i<orderVelocityPojo.getRange().size();i++){

                       countMap.put( ); 

                    }



                } catch (Exception e) {
                    Log.e("Exception",""+e);
                    utils.hideDialog();
                    e.printStackTrace();

                }
                utils.hideDialog();

            }, error -> {

        Log.e("error",""+error.getMessage());
        utils.hideDialog();
    });
    request.setRetryPolicy(new DefaultRetryPolicy(
            MY_SOCKET_TIMEOUT_MS,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    AppController.getInstance(this).addToRequestQueue(request);
}

OrderVelocityPojo Pojo类:

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class OrderVelocityPojo {

    @SerializedName("noOfIntervals")
    @Expose
    private Integer noOfIntervals;

    @SerializedName("range")
    @Expose
    private List<String> range = null; 


    public Integer getNoOfIntervals() {
        return noOfIntervals;
    }

    public void setNoOfIntervals(Integer noOfIntervals) {
        this.noOfIntervals = noOfIntervals;
    }

    public List<String> getRange() {
        return range;
    }

    public void setRange(List<String> range) {
        this.range = range;
    }
}

2 个答案:

答案 0 :(得分:2)

您可以使用Gson库。 您可以尝试将json对象转换为hashmap。在这里,您将提供typeToken作为您的json类型值。

Map<String, Object> hashmap = new Gson().fromJson(
    jsonString, new TypeToken<HashMap<String, Object>>() {}.getType()
);

答案 1 :(得分:1)

您还可以使用JSONObject的迭代键手动添加数据。

以下是示例代码。

        HashMap<String, String> count = new HashMap<>();
        HashMap<String, String> previousCountDay = new HashMap<>();
        try {
            JSONObject mJsonObjectMain = new JSONObject("your json string");
            JSONObject mJsonObjectCount = mJsonObjectMain.getJSONObject("count");
            Iterator a = mJsonObjectCount.keys();
            while (a.hasNext()) {
                String key = (String) a.next();
                // loop to get the dynamic key
                String value = (String) mJsonObjectCount.get(key);
                System.out.print("key : " + key);
                System.out.println(" value :" + value);
                count.put(key, value);
            }

            JSONObject mJsonObjectPreviousCount = mJsonObjectMain.getJSONObject("previousCountDay");
            //do same as above
        } catch (JSONException e) {
            e.printStackTrace();
        }

最终代码:

HashMap<String, Integer> count = new HashMap<>();
                     try {
                        JSONObject object = response.getJSONObject("count");
                        Iterator a = object.keys();
                        while (a.hasNext()) {
                            String key = (String) a.next();
                            // loop to get the dynamic key
                            Integer value = (Integer) object.get(key);
                            Log.e("count : ","Keys :"+ key+"   Values :"+value);
                            count.put(key, value);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }