假设我有一个 json 字符串,其中有一个名为 data 的 json 数组。该数组保存用户个人资料数据的 json 对象,例如姓名、年龄、性别等。
现在想要按顺序解析该 json 对象,例如,如果该对象是
{
"name": "sample name",
"age": "30",
"gender": "male"
}
Run Code Online (Sandbox Code Playgroud)
我想像name,age,genderios 一样按顺序解析列表,当我将 json 对象转换为字典时,顺序发生了变化,我知道字典没有排序,那么实现此目的的替代方法是什么?
它是第三方 api,所以我没有任何帮助,我们已经在 android 中使用链接哈希映射完成了它,但实际上陷入了 swift ,我想做的最后一件事就是用正则表达式进行解析。
我按以下方式解析 json:
var rootData = try JSONSerialization.jsonObject(with: data!) as! [String:Any]
if let val = fromList["data"] {
let dataNode = val as! [[String:Any]]
for row in dataNode {
for (key,keyVal) in row {
//here the key is not in order.because when we cast it as dictionary the order gets changed.
}
}
Run Code Online (Sandbox Code Playgroud)
对于 Android,我们已经通过以下功能实现了这一点:
public ArrayList<LinkedHashMap<String, Object>> parseJsonArrayList(String odata, String arrayName) {
ArrayList<LinkedHashMap<String, Object>> mylist = new ArrayList<>();
try {
JSONObject e = new JSONObject(odata);
JSONArray data = e.getJSONArray(arrayName);
for(int i = 0; i < data.length(); ++i) {
JSONObject v = data.getJSONObject(i);
LinkedHashMap<String, Object> map = new LinkedHashMap<>(100, 0.75f, false);
Iterator keys = v.keys();
while(keys.hasNext()) {
String key = String.valueOf(keys.next());
//gph.log("debug4", key);
map.put(key, v.getString(key));
//gph.log("debug4", v.getString(key));
}
mylist.add(map);
}
} catch (JSONException var10) {
var10.printStackTrace();
}
return mylist;
}
Run Code Online (Sandbox Code Playgroud)
Don\xe2\x80\x99t 尝试订购字典。相反,按照您想要的顺序创建一个键数组:
\n\nlet keys = [\xe2\x80\x9cname\xe2\x80\x9d, \xe2\x80\x9cage\xe2\x80\x9d, \xe2\x80\x9cgender\xe2\x80\x9d]\nRun Code Online (Sandbox Code Playgroud)\n\n然后用它们访问字典:
\n\nfor key in keys {\n let value = dict[key]\n // Present the value.\n}\nRun Code Online (Sandbox Code Playgroud)\n\n这将确保您期望的顺序。
\n| 归档时间: |
|
| 查看次数: |
2911 次 |
| 最近记录: |