2011-01-21 44 views
0

alt textAndroid將JSON數據解析爲HashTable?

我從Web服務獲取數據作爲JSON數據。顯示的數據顯示在圖像中:它基本上是一個名爲Questionnaire的類,它具有QuestionnaireId和QuestionnaireName兩個屬性。所以我調用的Web服務方法返回這個類問卷的集合。

我想這個數據解析到,我不能一個哈希表。請幫我把這個數據解析成Hashtable<QuestionnaireId,QuestionnaireName>

回答

1

你會想沿着這個線的東西:

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

(大約...)

+0

謝謝你工作完美:) – user581157 2011-01-21 12:00:33

3

我分析一些JSON字符串用這種方法,希望可以幫助您

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

我會推薦給不只是它塞進A 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對象來完成它添加到列表中。