如何将json反序列化为包含键和Object的hashmap?

时间:2015-08-20 14:37:22

标签: android json serialization hashmap json-deserialization

这是我的Json的形式:

{
"records": {
    "fastest": {
        "30": {
            "category": "fastest",
            "timestamp": 1407422694,
            "value": 2,
            "group_id": 30,
            "trip_id": 3429,
            "id": 28247
        },
        "42": {
            "category": "fastest",
            "timestamp": 1423570020,
            "value": -467,
            "group_id": 42,
            "trip_id": 9082,
            "id": 28040
        },
        "43": {
            "category": "fastest",
            "timestamp": 1410960788,
            "value": 16,
            "group_id": 43,
            "trip_id": 5138,
            "id": 28044
        },
        "46": {
            "category": "fastest",
            "timestamp": 1404286123,
            "value": 1609,
            "group_id": 46,
            "trip_id": 2524,
            "id": 28050
        }
    },
    "longest_flight": {
        "category": "longest_flight",
        "timestamp": 1434897403,
        "value": 1242203,
        "group_id": null,
        "trip_id": 12633,
        "id": 27950
    }
}
}

我知道如何获取longest_flight对象。但是我如何创建包含从"最快"创建的列表的hashmap。 json对象?

2 个答案:

答案 0 :(得分:1)

我不确定您是否在询问如何从URL获取JSONObject,或者如果您已经拥有JSONObject,如何只检索对象。所以这是两者的答案。

这从URL获取JSONObject:

import org.json.JSONException;
import org.json.JSONObject;

//attempts to open a connection to the specified url and returns a JSon response object
public JSONObject getResponseObject() {
    try {
        //Use URL connection 
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();


        conn.setRequestProperty("Accept", "application/json");


        // attempt the connection
        conn.connect();

        // Get the response code
        responseCode = conn.getResponseCode();

        // Check the response code, if the HTTP response code is 4nn
        // (Client Error) or 5nn (Server Error), then you may want to
        // read the HttpURLConnection#getErrorStream() to see if the
        // server has sent any useful error information.
        if (responseCode < 400) {

            // Get the response InputStream if all is well
            responseInputStream = conn.getInputStream();

            responseString = getResponseText(responseInputStream);

            try{
                responseObject = new JSONObject(responseString);
            }catch (JSONException et) {
                e.printStackTrace();
            }

            conn.disconnect();


        } else if (responseCode >= 400) {

            // Get the response ErrorStream if we got an error instead
            responseInputStream = conn.getErrorStream();
            conn.disconnect();
        }


    } catch (IOException e) {
       e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
 return responseObject;
}

您可以像这样解析responseObject:

JSONObject records = responseObject.getJSONObject("records");
JSONObject longestFlight = records.getJSONObject("longest_flight");
String id = longestFlight.getString("id");

迭代JSON中的键:

我应该提一下,您可能需要为JSON中的每个对象执行此操作。

Iterator<String> iter = json.keys();
while (iter.hasNext()) {
    String key = iter.next();
   try {
       Object value = json.get(key);
   } catch (JSONException e) {
       // Something went wrong!
   }
}

答案 1 :(得分:0)

从JSON返回一个arraylist的函数(因为该键也在对象内部,并且我不需要它用于我的逻辑) 代码:

 public static ArrayList<Record> sortedRecordsFromJson(String statsJson){
    try{
        Map map = new Gson().fromJson(statsJson, Map.class);
        ArrayList<Record> records = new ArrayList<>();
        Iterator it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pair = (Map.Entry)it.next();
            if(pair != null){
                Log.i("","pair : " + pair.toString());
                String json = pair.getValue().toString().replace(" ", "-");
                json = json.replace(",-", ", ");
                Log.i("","pair json is: " + json);
                JSONObject citiesObj = new JSONObject(json);
                Log.i("","cities obj " + citiesObj.toString());
                if(citiesObj != null){
                    Record tempMap = new Gson().fromJson(citiesObj.toString(), Record.class);
                    records.add(tempMap);
                }
            }
            it.remove(); // avoids a ConcurrentModificationException
        }
        Log.i("","got here, size:" + records.size());
        return records;
    }catch (Exception e){
        Log.i("","exception is: " + e.getMessage());
        return null;
    }
}

称之为:

   ArrayList fastest = Utils.sortedRecordsFromJson(statsJson.getJSONObject("fastest").toString());