2011-01-21 3 views
0

alt textAndroid에서 JSON 데이터를 HashTable로 구문 분석 하시겠습니까?

웹 서비스의 데이터를 JSON 데이터로 가져옵니다. 표시된 데이터는 이미지에 표시됩니다. 기본적으로 Questionnaire라는 클래스는 QuestionnaireId 및 QuestionnaireName이라는 두 가지 속성이 있습니다. 따라서 제가 호출하는 웹 서비스 메서드는이 클래스 설문지 모음을 반환합니다.

나는이 데이터를 내가 할 수없는 해시 테이블로 구문 분석하려고 시도하고있다. 이 데이터를 Hashtable<QuestionnaireId,QuestionnaireName>으로 구문 분석하도록 도와주세요.

답변

1

당신이의 라인을 따라 뭔가 할 것입니다 : 내가이 방법으로 몇 가지 JSON 문자열을 구문 분석 (... 대략)

+0

감사합니다. – user581157

3

Hashtable<Integer,String> table = new Hashtable<Integer,String>(); 

/* ... */ 

JsonObject root = new JsonObject(json_string); 
JsonArray questions = root.getJsonArray("d"); 
for(int i = 0; i < questions.length(); i++) { 
    JsonObject question = questions.getJsonObject(i); 
    int id = question.optInt("QuestionnaireId", -1); 
    String name = question.optString("QuestionnaireName"); 
    table.put(id, name); 
} 

을, 희망은 당신에게

public static Vector<MyObject> getImagesFromJson(String jos){ 
     Vector<MyObject> images = null; 
     try{ 

      JSONObject jo = new JSONObject(jos); 

      JSONArray array = jo.getJSONArray("images"); 
      if(array != null && array.length() > 0){ 
       images = new Vector<MyObject>(); 
      } 
      for (int i=0;i<array.length();i++) { 
       MyObject object = new MyObject(); 
       object.setEpigrafe(array.getJSONObject(i).get("epigrafe").toString()); 
       object.setId(array.getJSONObject(i).getInt("id")); 
       object.setUrl(array.getJSONObject(i).get("url").toString()); 
       images.add(object); 
      } 
     }catch(Exception e){ 
      images = null; 
      e.printStackTrace(); 
     } 
     return images; 
    } 

where MyObjects is defined as: 

    private int id; 
    private String url; 
    private String epigrafe; 
0

나는 M ap하지만 데이터를 POJO에 매핑 한 다음 해당 POJO로 List를 채 웁니다.

이와 같이 POJO를 정의하십시오.

public class Questionnaire { 

    private int id; 
    private String name; 

    public Questionnaire() { 
     setId(0); 
     setName(null); 
    } 

    public void setId(int id) { 
     this.id = id; 
    } 

    public int getId() { 
     return id; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    public String getName() { 
     return name; 
    } 
} 

Questionnaire 개체 목록을 만듭니다.

필요할 때마다 새로운 Questionnaire 개체를 만들고 설정자를 사용하여 구문 분석 된 데이터를 매핑합니다.

한 번 완료되면 Questionnaire 개체가 목록에 추가됩니다.