我不知道标题是否准确,但让我解释一下我想要什么。 我有这个很长的JSONObject(遗憾的是它不是一个数组,我不能遍历它),里面有许多其他JSONObjects,它们具有类似的元素(id,name,icon),当我读完一个元素时,它会写出它的值在一个单独的类中实现了Parcelable。 在我进一步解释之前,这是我的Parcelable类的样子:
public class ItemsInfo implements Parcelable {
public int itemId;
public String itemName, itemIcon;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(itemName);
dest.writeString(itemIcon);
dest.writeInt(itemId);
}
public static final Parcelable.Creator<ItemsInfo > CREATOR = new Parcelable.Creator<ItemsInfo >() {
@Override
public ItemsInfo createFromParcel(Parcel source) {
ItemsInfo ei = new ItemsInfo();
ei.itemName = source.readString();
ei.itemIcon = source.readString();
ei.itemId = source.readInt();
return ei;
}
@Override
public ItemsInfo [] newArray(int size) {
return new ItemsInfo [size];
}
};
}
我想要的是每次它通过具有相似元素的JSONObject读取时,用String itemName中的ArrayList写它们,所以稍后我只能通过索引或其他东西访问给定项目,而不必进行为每个不同的项目分隔字符串和整数,如itemName1,itemName2,itemName3 .....是否可能?
答案 0 :(得分:1)
您可以使用droidQuery来简化JSON
解析。要将JSONObject
转换为键值映射,您可以使用:
List<String> items = new ArrayList<String>();//this will contain your JSONObject strings
Map<String, ?> data = null;
try {
JSONObject json;//this references your JSONObject
data = $.map(json);
} catch (Throwable t) {
Log.e("JSON", "Malformed JSON Object");
}
然后,要遍历每个元素,只需执行以下操作:
if (data != null) {
for (Map.Entry<String, ?> entry : data.entrySet()) {
items.add(entry.value().toString());
}
}
现在,您的List
项将填充JSONObejct
的字符串表示形式。稍后,如果要解析此JSON,只需执行:
int index = 2;//the index of the JSONObject you want
try {
Map<String, ?> data = $.map(new JSONObject(items.get(2)));
//now iterate the map
} catch (Throwable t) {
t.printStackTrace();//something wrong with your JSON string
}