我想从此代码中获取男性对象,以便我的输出显示所有性别 有男性。
{
"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": "Johnny Depp",
"email": "johnny_depp@gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},
这是我试图获取的json代码
`if(jsonStr!= null){ 尝试{ JSONObject jsonObj = new JSONObject(jsonStr);
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
if(TAG_GENDER == male ){
String name = c.getString(TAG_GENDER);
HashMap<String, String> contact = new HashMap<String, String>();
contact.put(TAG_GENDER, name);
contactList.add(contact);
}} }
catch (JSONException e) {
e.printStackTrace();
}
}
else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}`
答案 0 :(得分:0)
这里“{”显示json对象和“[”显示json数组,所以我们将创建json对象,然后像jsonArray那样...
JSONObject jsonObj = new JSONObject(JsonObjectKey);
// if( jsonObj!=null)
// {
JSONArray list = jsonObj.getJSONArray("contacts");// here your json array aname
// if(list!=null)
for (int i = 0; i < list.length(); i++) {
//here you will fetch your all values that in your array..
}
答案 1 :(得分:0)
我正在修改你的for循环..
for (int i = 0; i < contacts.length(); i++)
{
JSONObject c = contacts.getJSONObject(i);
if((JSONObject)contacts.get(i)).get("gender").toString().equals("male") ){
String name = (JSONObject)contacts.get(i)).get("name").toString();
HashMap<String, String> contact = new HashMap<String, String>();
contact.put(TAG_GENDER, name);
contactList.add(contact);
}}
答案 2 :(得分:-1)
您需要进行一些修正。