Android 如何将json反序列化为包含键和对象的hashmap?
这是我的Json的格式:Android 如何将json反序列化为包含键和对象的hashmap?,android,json,serialization,hashmap,json-deserialization,Android,Json,Serialization,Hashmap,Json Deserialization,这是我的Json的格式: { "records": { "fastest": { "30": { "category": "fastest", "timestamp": 1407422694, "value": 2, "group_id": 30, "trip_id": 3429, "id": 28247 },
{
"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
}
}
}
我知道如何获得最长的飞行目标。但是,如何创建包含从“最快”json对象创建的列表的hashmap呢?我不确定您是在问如何从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;
}
要迭代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!
}
}
Iterator iter=json.keys();
while(iter.hasNext()){
String key=iter.next();
试一试{
Object value=json.get(key);
}捕获(JSONException e){
//出了点问题!
}
}
执行了一个函数,从JSON返回一个arraylist(因为键也在对象内部,我的逻辑不需要它)
代码:
想象一下,工程师们在没有google/stack的情况下就能解决这个问题。如果是你,我的朋友,你会被解雇的。你应该先考虑做谷歌搜索。安卓:你的问题。你的意思是说为meth这样做问题是id是动态的,在hashmap中得到大约200个值,比如“id”:{object}。现在我使用的是GSON,GSON有一种提取JSONARRAY或JSONOBJECT的方法。我想到了如何提取hashmap。但是,我不是第一个这样做的人。我说我会问,也许有人知道这个库(在ios上他们有这个库)。无论如何,没有找到一个图书馆,我发现谷歌上的例子对我没有帮助,我开始用我自己的方式去做。但这让我倒退了2-3个小时。我希望这不会发生。我使用截击来建立人际关系,你们也应该这样做,因为这样更容易使用。我还知道如何检索json对象。我的问题是我无法将我的JSONObject“Records”转换为class Record.class,因为我会得到所有的动态键(用于hashmap)。因此,我创建了下面的类,它通过json,只获取hashmap的值,然后为每个值创建一个类。在数组中设置它们,然后返回object:)interest的Arraylist。你看过谷歌图书馆吗?它允许直接从Json到类序列化,使用起来非常直观。我不确定它将如何处理像您正在尝试的那样序列化动态JSON对象,但可能值得一试。但Gson允许您直接从Json序列化到类JSONObject或JSONArray,但不适用于hashmaps。如果你看一下我在下面贴出的答案。你看,我在自己编写的代码中使用了Gson:DI dunno,我不做糟糕的JSON,我只是得到它并需要解析它。这就是iOS的实现方式,这就是我需要在Android上实现的方式,这是使用Android时令人讨厌的部分……在这种情况下,Json.keys()方法可能会派上用场。我把它添加到我上面的答案中。它应该允许您使用get函数创建具有值的哈希映射。这和你做的非常相似,只是线的抖动更少。
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = json.get(key);
} catch (JSONException e) {
// Something went wrong!
}
}
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());