2013-07-22 2 views
1

안녕하세요 저는 Android를 사용하는 웹 서비스가 처음입니다. 가치가 JSON에 존재하는지 어떻게 확인할 수 있습니까? 는 여기에 내가 이름 마이클 조던이 JSON에 존재하는 경우 알고 싶은 샘플 JSONandroid에서 JSON에 객체 값이 존재하는지 어떻게 알 수 있습니까?

{ 
    "contacts": [ 
    { 
      "id": "c200", 
      "name": "Michael Jordan", 
      "email": "[email protected]", 
      "address": "xx-xx-xxxx,x - street, x - country", 
      "gender" : "male", 
      "phone": { 
       "mobile": "+91 0000000000", 
       "home": "00 000000", 
       "office": "00 000000" 
      } 
    } 
    ] 
} 

입니다. 이걸로 나를 도와주세요. JSON에 객체가 있는지 확인하는 법만 알고 있습니다.하지만 값을 확인하고 싶다면 어떻게해야합니까?

+0

http://jsonlint.com/ 사용 json validator – Giant

답변

3

콘텐츠를 JSONObject로 읽어야합니다. 그런 다음이 코드 스 니펫을 추가 할 수 있습니다.

JSONArray jsonArray = yourJSONObject.getJSONArray("contacts"); //here yourJSONObject is the object which has the array in your question. 
for(int i = 0; i<jsonArray.length(); i++) { 
JSONObject jObject = jsonArray.getJSONObject(i); 
String name = jObject.getString("name"); 
if(name.equals("Michael Jordan")) { 
System.out.println("Name Exists"); 
} 
} 
+0

감사합니다. – NewDroidDev

0

은 그냥 문자열을 검색 할 수 없습니다? contains 함수를 살펴보십시오. 그렇지 않으면 gson을 살펴보십시오. 객체에 json을 직렬화 할 수 있습니다.

2

확장 할 수있는 범위를 잘 모르지만 입력 스트림을 성공적으로 구문 분석하여 JSONObject에 입력했다고 가정 해 봅니다.

public boolean isJordanHere(JSONObject root) { 
    try { 
     JSONArray contacts = root.getJSONArray("contacts"); 
     for(int i=0; i<contacts.length(); i++) 
     { 
      String name = contacts.getJSONObject(i).getString("name"); 
      if("Michael Jordan".equals(name)) 
      { 
       return true; 
      } 
     } 
    } catch (JSONException e) { 
     e.printStackTrace(); 
     return false; 
    } 

    return false; 
} 
관련 문제