【问题标题】:Issue converting JSON to HashMap in Android在 Android 中将 JSON 转换为 HashMap 的问题
【发布时间】:2011-11-27 09:41:17
【问题描述】:

我有JSONArray,当我将JSON解码为HashMap时,HashMap取最后一个值JSONArray

这是我的代码:

QjArray = new JSONArray(Questionresult);
JSONObject json_data  = new JSONObject();
for (int i = 0; i<QjArray.length(); i++) {
    objJMap = new HashMap<String, String>(); 
    json_data = QjArray.getJSONObject(i);

    jQuestionName =json_data.getString("QuestionName");
    objJMap.put("QuestionName",jQuestionName);

    jQuestiontypeid = json_data.getInt("Questiontypeid");
    String Qid = jQuestiontypeid.toString();
    objJMap.put("Questiontypeid", Qid);

    jAnswertypeid = json_data.getInt("Answertypeid");
    String Aid = jAnswertypeid.toString();
    objJMap.put("Answertypeid", Aid);
}

我的JSONArray

This is question list[{"QuestionID":"1","QuestionName":"when you come","Questiontypeid":"1","Answertypeid":"1"},{"QuestionID":"2","QuestionName":"about your words","Questiontypeid":"1","Answertypeid":"2"},{"QuestionID":"3","QuestionName":"you want extra service?","Questiontypeid":"1","Answertypeid":"3"},{"QuestionID":"4","QuestionName":"performance of quality ?","Questiontypeid":"1","Answertypeid":"4"},{"QuestionID":"5","QuestionName":"performance of staff?","Questiontypeid":"1","Answertypeid":"5"},{"QuestionID":"6","QuestionName":"when you left room ?","Questiontypeid":"2","Answertypeid":"1"},{"QuestionID":"7","QuestionName":"your words about roomservice ?","Questiontypeid":"2","Answertypeid":"2"},{"QuestionID":"8","QuestionName":"you like roomservice ?","Questiontypeid":"2","Answertypeid":"3"},{"QuestionID":"9","QuestionName":"performance room service ?","Questiontypeid":"2","Answertypeid":"4"},{"QuestionID":"10","QuestionName":"performance room service staff?","Questiontypeid":"2","Answertypeid":"5"}]

【问题讨论】:

    标签: android json hashmap type-conversion


    【解决方案1】:

    我认为您的逻辑存在某些问题。对于每个 JSON 对象,您都在 for 循环中创建新的 HashMap 对象,因此您将丢失任何以前的数据。 HashMap 也将覆盖新数据,因此您将只有最终数据。你可以做的是创建一个Hashmap的arrayList ....

         ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<STring, String>>();
        for (int i = 0; i<QjArray.length(); i++) {
    
               objJMap = new HashMap<String, String>(); 
    ........
               data.add(objJMap);
        ...}
    

    【讨论】:

    • 现在是 arraylist 中的 json 代码,现在如何迭代该 arraylist?
    • 我现在完成了如何迭代 Arraylist ?如何使用它??
    • 你可以很容易找到它,只需搜索一下
    【解决方案2】:

    这是因为您的代码在每次循环后都会重新初始化 HashMap。

    for (int i = 0; i<QjArray.length(); i++) {
                 objJMap = new HashMap<String, String>(); 
    ....
    }
    

    将 HashMap 放在循环之外,它会正常工作。

    objJMap = new HashMap<String, String>(); 
    for (int i = 0; i<QjArray.length(); i++) {
    ....
    }
    

    【讨论】:

      猜你喜欢
      • 2013-03-02
      • 1970-01-01
      • 1970-01-01
      • 2013-02-07
      • 1970-01-01
      • 2019-10-24
      • 1970-01-01
      • 2016-12-07
      • 1970-01-01
      相关资源
      最近更新 更多