Reputation: 2564
I don't know of the title is very accurate, but let me explain what I want. I am having this long JSONObject (sadly it's not an array and I can't loop through it) with many other JSONObjects inside of it with similar elements (id, name, icon), and when I read through an element it writes its value in a separate class with implemented Parcelable. Here is what my Parcelable class look like before I explain further:
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];
}
};
}
what I want is everytime it reads through a JSONObject with the similar elements, to write them with an ArrayList in the String itemName, so later I can access a given item by only a index or something, and not to have to make separate strings and integers for every different item, like itemName1, itemName2, itemName3..... Is it possible?
Upvotes: 0
Views: 2550
Reputation: 36289
You can use my droidQuery library to simplify JSON
parsing. To convert your JSONObject
to a Key-Value mapping, you can use this:
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");
}
Then, to loop through each element, just do this:
if (data != null) {
for (Map.Entry<String, ?> entry : data.entrySet()) {
items.add(entry.value().toString());
}
}
Now your List
items is populated with the String representation of your JSONObejct
s. Later, if you want to parse this JSON, just do:
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
}
Upvotes: 1