简体   繁体   中英

Android JSON parsing parcelable for list

My JSON looks like this -

{
  "item1": {
    "id": "1",
    "color": "yellow",
    "functionality": [
{
  "name": "press",
  "option": "start"
},
{
  "name": "touch"
  "option": "end"
}
]
  }
}

Here is my Parcelable code.

I want to access functionality in my Java code but I need some help of how I could do this.

public class MyData implements Parcelable {


    private Map<String, String> item1;

    protected MyData(Parcel in) {

        int item1Size = in.readInt();
        item1 = new HashMap<>(item1Size);

        for (int i = 0; i < item1Size; i++) {

            String key = in.readString();
            String value = in.readString();
            this.item1.put(key, value);
        }
    }

    public String getItem1Detail(String key) {

        if (item1 != null && item1.containsKey(key)) {

            return item1.get(key);
        }

        return null;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {

        if (item1 != null) {
            dest.writeInt(this.item1.size());

            for (Map.Entry<String, String> entry : this.item1.entrySet()) {

                dest.writeString(entry.getKey());
                dest.writeString(entry.getValue());
            }
        } else {
            dest.writeInt(0);
        }

    }

    public String getId(Map<String, String> collection) {
        return collection != null ? collection.get("id") : null;
    }

    public String getColor(Map<String, String> collection) {
        return collection != null ? collection.get("color") : null;
    }

}

Can anyone tell me please how I could access functionality from my json...

How my Parcelable class should look like?

I want to use it for PUT and GET the same JSON structure.

Android JSON parsing parcelable for list

I would recommend making a model of your item class. Something like:

class Item {
   private int id;
   private String color;
   private ArrayList<Function> functionality = new ArrayList<>();
}

class Function {
   private String name;
   private String option;
}

That way, we can use the Gson library to easily parse your JSON object.

Item model = gson.fromJson(jsonAsString, Item.class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM