2013-10-11 3 views
1

Я хочу, чтобы создать такую ​​формуСформировать JSONObject динамически в андроиде

{ 
"dt": { 
    "DocumentElement": [ 

      { 
       "CompanyID": "8", 
       "Question": "Who I M?", 
       "Answer": "dfsfdsfd" 

     }, 
     { 

       "CompanyID": "8", 
       "Question": "Who I M?", 
       "Answer": "Chintan" 

     } 
    ] 
    } 
} 

У меня есть один ArrayList, который динамически заполненные данные, и я также хочу форму с точкой зрения динамического. Вот мой код:

JSONObject DocumentElementobj = new JSONObject(); 
     JSONArray req = new JSONArray(); 

     JSONObject reqObj = new JSONObject(); 
     try { 
      for (int i = 0; i < OnLineApplication.mParserResults.size(); i++) { 


       reqObj.put("CompanyID", "8"); 
       reqObj.put("Question",OnLineApplication.mParserResults.get(i).getQuestion()); 
       reqObj.put("Answer",OnLineApplication.mParserResults.get(i).getAnswer()); 

      } 


      DocumentElementobj.put("DocumentElement", req); 
      System.out.println("Final "+DocumentElementobj.toString()); 
     } catch (JSONException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 

Он выводит: Final { "DocumentElement": []}

EDIT

Спасибо всем, ваш ответ. По всем вам Быстродействие я сделать код, как показано ниже

JSONObject DocumentElementobj = new JSONObject(); 
     JSONArray req = new JSONArray(); 
     JSONObject reqObjdt = new JSONObject(); 

     try { 
      for (int i = 0; i < OnLineApplication.mParserResults.size(); i++) { 

       JSONObject reqObj = new JSONObject(); 
       reqObj.put("CompanyID", OnLineApplication.mParserResults.get(i).getCompanyId()); 
       reqObj.put("Question",OnLineApplication.mParserResults.get(i).getQuestion()); 
       reqObj.put("Answer",OnLineApplication.mParserResults.get(i).getAnswer()); 
       req.put(reqObj); 


      } 



      DocumentElementobj.put("DocumentElement", req); 
      reqObjdt.put("dt", DocumentElementobj); 
      System.out.println("Final "+reqObjdt.toString()); 
     } catch (JSONException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 

Я получаю foramt, который я хочу, но в конечной строке, я получаю sequeence, как показано ниже

{"dt": 
    {"DocumentElement": 
    [ 
    {"Answer": "The Claims Representatives have a small role in return to work.","Question":"Return-to-Work Claim Issues. Please check the statement that best applies.","CompanyID":"8"}, 
    {"Answer":"Poor","Question":"How would you describe the level of your general employee’s understanding of the impact of workers’ compensation costs on your organization?","CompanyID":"8"}]}} 

речь идет Ответ первой в последовательности, но я хочу сначала в CompanyID, так что в этом проблема?

+0

Что вы делаете с REQ? Ничего? Вы добавляете материал в reqObj, но вы ничего не делаете с ним –

ответ

1

Вы забыли добавить JSONObjectreqObj в JSONArrayreq. как req.put(reqObj);.

Измените блок кода с for loop, как

JSONObject reqObj = new JSONObject(); // Move inside the loop 
reqObj.put("CompanyID", "8"); 
reqObj.put("Question",OnLineApplication.mParserResults.get(i).getQuestion()); 
reqObj.put("Answer",OnLineApplication.mParserResults.get(i).getAnswer()); 
req.put(reqObj); // ADDED HERE 
+0

. Я добавляю req.put (reqObj) внутри цикла, но каждый раз получаю последние данные arraylist с соответствующим размером arraylist. –

+0

Move 'JSONObject reqObj = new JSONObject();' in loop , См. Мой ответ –

+0

@HarshalKalavadiya. Вы должны действительно рассмотреть использование отладчика, особенно если вы работаете с использованием студии eclipse/android. Вы легко поймете эти проблемы. –

1

Существует очень хороший Google Libray, называемый gson, который поможет вам с легкостью создать Json Object или Parse Json Object.

Вам необходимо добавить файл gson.jar в свой проект.

Для получения более подробной информации ознакомьтесь с приведенной ниже ссылкой.

https://sites.google.com/site/gson/gson-user-guide

Отредактированный Ответ: -

public class DocumentElement { 
    @Expose 
    private String CompanyID; 
    @Expose 
    private String Question; 
    @Expose 
    private String Answer; 

    public DocumentElement(String CompanyID, String Question, String Answer) { 
     this.CompanyID = CompanyID; 
     this.Question = Question; 
     this.Answer = Answer; 
    } 

    public String getCompanyID() { 
     return CompanyID; 
    } 

    public String getQuestion() { 
     return Question; 
    } 

    public String getAnswer() { 
     return Answer; 
    } 

} 

public class Data { 
    @Expose 
    private ArrayList<DocumentElement> DocumentElement; 

    public ArrayList<DocumentElement> getDocumentElement() { 
     return DocumentElement; 
    } 

    public void setDocumentElement(ArrayList<DocumentElement> DocumentElement) { 
     this.DocumentElement = DocumentElement; 
    } 

} 


public class ParentData { 
    @Expose 
    private Data dt; 

    public Data getDt() { 
     return dt; 
    } 

    public void setDt(Data dt) { 
     this.dt = dt; 
    } 

} 

и используется, как это создать JSONObject по помощи gson.jar

ArrayList<DocumentElement> doc=new ArrayList<DocumentElement>(); 
     DocumentElement doc1=new DocumentElement("8", "Who I M?", "Amit"); 
     DocumentElement doc2=new DocumentElement("9", "Who I M?", "Gupta"); 
     doc.add(doc1); 
     doc.add(doc2); 
     Data data=new Data(); 
     data.setDocumentElement(doc); 
     ParentData parent=new ParentData(); 
     parent.setDt(data); 
     Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); 
     String jsonObj = gson.toJson(parent); 
     System.out.println("createdJson:---"+jsonObj); 

Результат являются

{"dt":{"DocumentElement":[{"Answer":"Amit","CompanyID":"8","Question":"Who I M?"},{"Answer":"Gupta","CompanyID":"9","Question":"Who I M?"}]}} 

Надеюсь, это вам подойдет.

+0

На самом деле он не отвечает на вопрос. –

+0

@Amit Gupta: см. Раздел «Редактировать блок». –

1

Вы не добавить reqObj к REQ.

ли req.put(reqObj)

JSONObject documentElementobj = new JSONObject(); 
    JSONArray req = new JSONArray(); 


    try { 
     for (int i = 0; i < OnLineApplication.mParserResults.size(); i++) { 

      JSONObject reqObj = new JSONObject(); 
      reqObj.put("CompanyID", "8"); 
      reqObj.put("Question",OnLineApplication.mParserResults.get(i).getQuestion()); 
      reqObj.put("Answer",OnLineApplication.mParserResults.get(i).getAnswer()); 
      req.put(reqObj); 
     } 


     documentElementobj.put("documentElement", req); 
     System.out.println("Final "+ documentElementobj.toString()); 
    } catch (JSONException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 

Кроме того, это лучше сделать ваши переменные начинаются со строчной буквы, как правило.

В этом случае будет эффективнее использовать отладчик.

+0

: см. Раздел «Редактировать блок». –

+0

Вам не нужно заботиться об этом. Это ничего не изменит в том, как вы разбираете. –

+0

: Спасибо за ваши усилия !!! –

0

Используйте этот код, чтобы FULLFILL ответ:

 JSONObject jObj = new JSONObject("Your web Response"); 

     JSONObject jObj1 = jObj.getJSONObject("dt"); 

     JSONArray item = jObj.getJSONArray("DocumentElement"); 

     for (int i = 0; i < item.length(); i++) 
     { 
      jObj_data = (JSONObject) item.get(i); 
      reqObj.put("CompanyID", jObj_data.getString("CompanyID")); 
      reqObj.put("Question",jObj_data.getString("Question")); 
      reqObj.put("Answer",jObj_data.getString("Answer")); 
     } 
+0

Неправильно нет? –

Смежные вопросы