如何引用JSON android中的特定项?

时间:2017-03-31 20:04:24

标签: android json listview

我正在关注Android中的JSON教程。我设法将文件中的JSON输出到ListView。但是,我不太明白具体项目的工作原理。 这是json文件:

    {
  "contacts": [
    {
      "id": "c200",
      "name": "Ravi Tamada",
      "email": "ravi@gmail.com",
      "address": "xx-xx-xxxx,x - street, x - country",
      "gender" : "male",
      "phone": {
        "mobile": "+91 0000000000",
        "home": "00 000000",
        "office": "00 000000"
      }
    },
    {
      "id": "c201",
      "name": "Figaro",
      "email": "figaro@gmail.com",
      "address": "xx-xx-xxxx,x - street, x - country",
      "gender" : "male",
      "phone": {
        "mobile": "+91 0000000000",
        "home": "00 000000",
        "office": "00 000000"
      }
    },
    {
      "id": "c202",
      "name": "Johnny Depp",
      "email": "johnny_depp@gmail.com",
      "address": "xx-xx-xxxx,x - street, x - country",
      "gender" : "female",
      "phone": {
        "mobile": "+91 0000000000",
        "home": "00 000000",
        "office": "00 000000"
      }
    }
  ]
}

第一件事:如何输出项目,例如" gender = male"只要? 第二件事:每当我在我的ListView中按Ravi Tamada为例时,我怎么能让它只加载它的移动设备?换句话说,如何设置我按下的项目和应该显示的信息之间的链接,同时考虑到它与被按下项目的关系?

这就是我从json中检索项目的方法:

 switch (view.getId()){

            case R.id.button1:
                loadmyjson();
                try {
                    JSONObject jsonObj = new JSONObject(jsonString);

                    JSONArray letters = jsonObj.getJSONArray("contacts");
                    for (int i = 0; i < letters.length(); i++){
                        JSONObject first = letters.getJSONObject(i);
                        String gender = first.getString("gender");
                        Log.e("and that means", " " + gender);

                        if (first.getString("name") == "Figaro"){
                            where.add(gender);


                        }

                         }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Log.e("and that means", " " + where);

                break;

        }

问题是这个if语句总是错误的。

1 个答案:

答案 0 :(得分:2)

而是first.getString("name") == "Figaro"尝试first.getString("name").equals("Figaro")