繁体   English   中英

Android JSON解析可拆分列表

[英]Android JSON parsing parcelable for list

我的JSON看起来像这样-

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

这是我的包裹代码。

我想访问Java代码中的functionality ,但是我需要一些如何做的帮助。

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;
    }

}

谁能告诉我如何从json访问functionality ...

我的Parcelable类应该是什么样?

我想将其用于PUT和GET相同的JSON结构。

Android JSON解析可拆分列表

我建议为您的项目类别建立模型。 就像是:

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

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

这样,我们可以使用Gson库轻松解析您的JSON对象。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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