这是我的json结构
{
"menus": [
{
"sequence":"1",
"Name":"Sector"
},
{
"sequence":"3",
"Name":"Segment"
},
{
"sequence":"2",
"Name":"Collection"
}
]
}
如何按顺序解析/存储1,2,3等数据?
答案 0 :(得分:0)
私有字符串序列;
私人字符串名称;
public String getSequence() {
return sequence;
}
public void setSequence(String sequence) {
this.sequence= sequence;
}
public String getName() {
return name;
}
public void setName(String name) {
this.Name= name;
}
}
2.然后像下面那样解析你的Json值
列出menuslist = new ArrayList();
尝试{
JSONObject jObject = new JSONObject(result.toString);
JSONArray array = jObject.getJSONArray(“menus”);
for(int i = 0; i
JSONObject Object = array.JSONObject(i);
菜单菜单=新菜单();
menus.setSequence(Object.getString( “序列”));
menus.setName(Object.getString( “名称”));
menuslist.add(菜单);
}
}
catch(JSONException Je) {
je.printexception;
}
答案 1 :(得分:0)
在列表中解析数组
JSONArray sortedJsonArray = new JSONArray();
List<JSONObject> jsonList = new ArrayList<JSONObject>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonList.add(jsonArray.getJSONObject(i));
}
然后使用collection.sort对新创建的列表进行排序
Collections.sort( jsonList, new Comparator<JSONObject>() {
public int compare(JSONObject a, JSONObject b) {
String valA = new String();
String valB = new String();
try {
valA = (String) a.get("sequence");
valB = (String) b.get("sequence");
}
catch (JSONException e) {
//do something
}
return valA.compareTo(valB);
}
});
在数组中插入已排序的值
for (int i = 0; i < jsonArray.length(); i++) {
sortedJsonArray.put(jsonList.get(i));
}
答案 2 :(得分:0)
我使用了TreeMap。
Map sequenceMenuOrder = new TreeMap<String, String>();
int position = 0;
for (int index = 0; index < menus.length(); index++) {
sequenceMenuOrder.put(menus.getJSONObject(index).getString("sequence"), menus.getJSONObject(index).getString("menuName"));
}
for (Object value : sequenceMenuOrder.keySet()) {
if (position != 0) {
menuString += ",";
}
menuString += sequenceMenuOrder.get(value);
position++;
}