如何将 json 反序列化为包含键和对象的哈希映射?

How can I deserialize a json into a hashmap that contains a key and a Object?

这是我的 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 对象。但是如何创建包含从 "fastest" json 对象创建的列表的哈希图?

我不确定您是在问如何从 URL 中获取 JSONObject 还是在已经拥有 JSONObject 后如何检索对象.所以这里是两者的答案。

这从 URL 获取一个 JSON对象:

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

做了一个 returns arraylist 的函数,来自 JSON (因为键也在对象内部,我的逻辑不需要它) 代码:

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