Survey API Reference

What is an API Key? Where can I get an API Key?

An application programing interface key (API key) is a code generated by websites that allow users to access their application programming interface. To generate an API key,

Go To :

  • $crumb.fullText

Click on Register New API Key and the key will be generated. Use this key for setting up API integration.
Survey Software Help Image

What is Device Key? Where can I get a Device Key?

A device key is a code generated by websites that allow users to access their application programming interface. To generate a Device Key,

Go To :

  • Login »  Surveys »  Mobile »  SurveyPocket™ »  Device Registration

Step1: Click on Add Device Key and then Add New Device Key popup will appear.

Step2: Enter the Name of device key.

Step3: Click on Save Device Key and the key will be generated.

Survey Software Help Image

How does API integration work?

All of our requests are done with the HTTP POST method and are accompanied with a JSON payload. Based on parameters received through a JSON request body, the API will execute the function specified in the API call. The response will be returned in the form of JSON. The attributes passed in the JSON payload must have at least survey ID. We can add additional attributes to further refine the request (eg. Start Date and End Date etc).

Base URL : http://api.surveyanalytics.com/a/api/

API key parameter name : apiKey

Device key parameter name : deviceKey

Example API call URL: http://api.surveyanalytics.com/a/api/surveyanalytics.survey.surveyResponses?apiKey=542f01cf-1dec-45b7-87c3-114496681006&deviceKey=muixi

We serve only 500 responses per API call

API Calls available:

1) surveyResponses

Purpose

You can use this surveyResponses API to retrieve responses based on the filtering criteria

Request URL

www.surveyanalytics.com/a/api/surveyanalytics.survey.surveyResponses?apiKey={API-KEY}&deviceKey=DEVICE-KEY

Request Parameters
Parameter DataType Description
apiKey* String Encrypted alphanumeric string to authenticate your credentials.
deviceKey* String A device key is a code generated by websites that allow users to access their application programming interface

* - Mandatory parameter

JSON Data Format

The JSON Format contains the key value pair of the required parameter.

Input JSON Parameters :
Parameter Description
id* Survey ID
resultMode Result Mode can be any of All/Completed/Started/Terminated. Possible Values- (i) All - 0 (Default) (ii) Started but Not Completed - 1 (iii) Completed - 2 (iv) Terminated via Branching - 3 (Optional)
startingResponseCounter Pager no. for the responses. Each pager will have maximum of 500 responses. For e.g. startingResponseCounter = 0 will return 0-500 response and startingResponseCounter = 1 will return 501-1000 response (if survey has up to 1000 responses for specified criteria). If not specified default is taken as 0.
startDate Start Date for response time range. Date Format must be MM/DD/YYYY. (Optional)
endDate End Date for response time range.Date Format must be MM/DD/YYYY. (Optional)
NOTE:

    * - Mandatory parameter.

    All the parameter names are Case Sensitive.

Either both Start Date and End Date have to be entered else neither
Input JSON Example:
 {"id":3119678, "startingResponseCounter":0, "resultMode":0, "startDate":"01/01/2013", "endDate":"07/20/2013"} 

Response (Output) JSON Parameters :

Parameter Description
id Survey ID
name Survey Name
responseCount Total response count
responses This is JSON array of responses
metaData This is JSON array of meta data of questions
Parameters for "responses" array:
Parameter Description
responseID This is the response ID
timestamp Survey response timestamp
timeTaken Time taken to complete the survey
ipAddress This is an IP address of the respondent
results This is JSON array of the results
customVariables This is JSON array for the custom variables details
Parameters for "results" array:
Parameter Description
questionID This is the question ID
index Index of the question
Parameters for "customVariables" array:
Parameter Description
index This is an index of custom variable
value This is the value of the custom variable
Parameters for "metaData" array:
Parameter Description
questionID This is the question ID
questionText This represents the question text
hasRank This indicates whether the question belongs to Rank Order type. Visible only for Rank Order question
answers This is a JSON array of answers details
Parameters for "answers" array
index This is an index of an answer
answerText This represents the answer text
Response (Output) JSON Example:
 {
                "response":{
                "id":3643,
                "name":"Survey API Test",
                "responseCount":1,
                "responses":[
                {
                "timestamp":"Tue Jul 16 05:43:34 GMT+05:30 2013",
                "responseID":26699,
                "results":[
                {
                "index":5,
                "questionID":17597895
                },
                {
                "text":"Other single select",
                "index":5,
                "questionID":17597895
                },
                {
                "text":"",
                "index":3,
                "questionID":17597895
                },
                {
                "index":2,
                "questionID":17597896
                },
                {
                "index":4,
                "questionID":17597896
                },
                {
                "index":5,
                "questionID":17597896
                }
                ],
                "customVariables":[{"index":2,"value":"custom2 test value"},{"index":6,"value":"custom6 test value"}],
                "timeTaken":13,
                "ipAddress":"127.0.0.1"
                }
                ],
                "metaData":[
                {
                "questionID":17597895,
                "questionText":"Single select Question",
                "answers":[{"index":1,"answerText":"first"},{"index":2,"answerText":"second "},{"index":3,"dynamicText":true,"answerText":"third"},{"index":4,"dynamicText":true,"answerText":"fourth"},{"index":5,"other":true,"answerText":"Other"}]
                },
                {
                "questionID":17597896,
                "questionText":"Multiple Select Question",
                "answers":[{"index":1,"answerText":"Visa"},{"index":2,"answerText":"Mastercard"},{"index":3,"answerText":"American Express"},{"index":4,"answerText":"Discover"},{"index":5,"answerText":"Diners Club"},{"index":6,"other":true,"answerText":"Other"}]
                },
                {
                "questionID":17597897,
                "questionText":"Please rank (1-3) the following in order of interest:",
                "answers":[{"index":1,"answerText":"Skiing"},{"index":2,"answerText":"Snowboarding"},{"index":3,"answerText":"Biking"}],
                "hasRank":true
                },
                {
                "questionID":17597898,
                "questionText":"First Name",
                "answers":[{"index":1,"answerText":"FIRST_NAME"}]
                },
                {
                "questionID":17597899,
                "questionText":"Last Name",
                "answers":[{"index":1,"answerText":"LAST_NAME"}]
                },
                {
                "questionID":17597900,
                "questionText":"Address 1",
                "answers":[{"index":1,"answerText":"ADDRESS"}]
                },
                {
                "questionID":17597901,
                "questionText":"Address 2",
                "answers":[{"index":1,"answerText":"ADDRESS2"}]
                },
                {
                "questionID":17597902,
                "questionText":"City",
                "answers":[{"index":1,"answerText":"CITY"}]
                },
                {
                "questionID":17597903,
                "questionText":"State",
                "answers":[{"index":1,"answerText":"STATE"}]
                },
                {
                "questionID":17597904,
                "questionText":"Zip",
                "answers":[{"index":1,"answerText":"ZIP"}]
                },
                {
                "questionID":17597905,
                "questionText":"Phone",
                "answers":[{"index":1,
                "answerText":"PHONE"}]
                },
                {
                "questionID":17597906,
                "questionText":"Email Address",
                "answers":[{"index":1,"answerText":"EMAIL"}]
                }
                ]
                },
                "status":{
                "message":"OK",
                "id":200,
                "method":"surveyanalytics.survey.surveyResponses",
                "serverUTC":1374477777825,
                "url":"/a/api/surveyanalytics.survey.surveyResponses",
                "apiKey":"77407dc0-9c05-4d5d-afe6-1d65c15ada64"
                }
                }

2) responseCount

Purpose

You can use this responseCount API to get started, terminated and completed response count for the specified survey and criteria.

Request URL

www.surveyanalytics.com/a/api/surveyanalytics.survey.responseCount?apiKey={API-KEY}&deviceKey=DEVICE-KEY

Request Parameters
Parameter DataType Description
apiKey* String Encrypted alphanumeric string to authenticate your credentials.
deviceKey* String A device key is a code generated by websites that allow users to access their application programming interface

* - Mandatory parameter

JSON Data Format

The JSON Format contains the key value pair of the required parameter.

Input JSON Parameters :
Parameter Description
id* Survey ID
startDate Start Date for response time range. Date Format must be MM/DD/YYYY. (Optional)
endDate End Date for response time range.Date Format must be MM/DD/YYYY. (Optional)
NOTE:

    * - Mandatory parameter.

    All the parameter names are Case Sensitive.

Either both Start Date and End Date have to be entered else neither
Input JSON Example:
 {"id":3119678, "startDate":"01/01/2013", "endDate":"07/20/2013"} 

Response (Output) JSON Parameters :

Parameter Description
id Survey ID
name Survey Name
startedCount Survey started count
completeCount Survey terminated count
completeCount Survey completed count
Response (Output) JSON Example:
  {"response":{"id":3643,"name":"Survey API Test","startedCount":3,"terminatedCount":0,"completeCount":3},"status":{"message":"OK","id":200,"method":"surveyanalytics.survey.responseCount","serverUTC":1374483638575,"url":"/a/api/surveyanalytics.survey.responseCount","apiKey":"77407dc0-9c05-4d5d-afe6-1d65c15ada64"}}

3) sendSurvey

Purpose

You can use this sendSurvey API to send survey to single respondent.

Request URL

www.surveyanalytics.com/a/api/surveyanalytics.survey.sendSurvey?apiKey={API-KEY}&deviceKey=DEVICE-KEY

Request Parameters
Parameter DataType Description
apiKey* String Encrypted alphanumeric string to authenticate your credentials.
deviceKey* String A device key is a code generated by websites that allow users to access their application programming interface

* - Mandatory parameter

JSON Data Format

The JSON Format contains the key value pair of the required parameter.

Input JSON Parameters :
Parameter Description
id* Survey ID
sendToEmailAddress* Email address of the respondent. It has to be of the format user@domain.name
sendToEmailText Email text/body (Optional)
sendToEmailSubject Email subject (Optional)
NOTE:

    * - Mandatory parameter.

    All the parameter names are Case Sensitive.

Input JSON Example:
  {"id":3643, "sendToEmailAddress": "test@survey.com", "sendToEmailText":"hello, test email.", "sendToEmailSubject":"test email subject"}

Response (Output) JSON Parameters :

Parameter Description
id Survey ID
name Survey Name
sendToEmailAddress Email address of the respondent
success Description of the status of email sent
Response (Output) JSON Example:
                {
                "response":{
                "id":3643,
                "name":"Survey API Test",
                "sendToEmailAddress":"test1@test.com",
                "success":"Email Successfully Sent"
                },
                "status":{
                "message":"OK",
                "id":200,
                "method":"surveyanalytics.survey.sendSurvey",
                "serverUTC":1374484093534,
                "url":"/a/api/surveyanalytics.survey.sendSurvey",
                "apiKey":"77407dc0-9c05-4d5d-afe6-1d65c15ada64"
                }
                }
            

4) surveyStatistics

Purpose

You can use this surveyStatistics API to retrieve the survey statistics for the specified survey.

Request URL

www.surveyanalytics.com/a/api/surveyanalytics.survey.surveyStatistics?apiKey={API-KEY}&deviceKey=DEVICE-KEY

Request Parameters
Parameter DataType Description
apiKey* String Encrypted alphanumeric string to authenticate your credentials.
deviceKey* String A device key is a code generated by websites that allow users to access their application programming interface

* - Mandatory parameter

JSON Data Format

The JSON Format contains the key value pair of the required parameter.

JSON Parameters :
Parameter Description
id* Survey ID
resultMode Result Mode can be any of All/Completed/Started/Terminated. Possible Values- (i) All - 0 (ii) Started but Not Completed - 1 (iii) Completed - 2 (iv) Terminated via Branching - 3 (Optional)
startDate Start Date for response time range. Date Format must be MM/DD/YYYY. (Optional)
endDate End Date for response time range.Date Format must be MM/DD/YYYY. (Optional)
NOTE:

    * - Mandatory parameter.

    All the parameter names are Case Sensitive.

Either both Start Date and End Date have to be entered else neither
Input JSON Example:

{"id":3119678, "resultMode":0, "startDate":"01/01/2013", "endDate":"07/20/2013"}

Response (Output) JSON Parameters :

Parameter Description
surveyID Survey ID
surveyName Survey Name
viewedCount Survey viewed count
dropOutCount Surveys drop out count
startedCount Survey start count
terminatedCount Survey terminated count
completionRate Survey completion rate in percentage
averageTimeInSeconds Average time of survey in seconds
completeCount Survey completed count
surveyStatistics It is a JSON Array of sections which contains questions and their answers
Parameters for "surveyStatistics" array:
Parameter Description
sectionID This represents the ID of the section
description This describes the section. For Side by Side (Multi Dimension) Matrix question this is a JSON array describing the sub sections of the question.
type The question type
questions This is a JSON array of questions
Parameters for "description" array (Only for Side by Side (Multi Dimension) Matrix Question)
Parameter Description
mdmSectionNum This is the sub section number within the question
subHeading This is the sub heading of the sub section
title This is the title of the sub section
Parameters for "questions" array:
Parameter Description
id This is question ID
text This is question text (question description)
mdmSectionNum This is the sub section number within the Side by Side (Multi Dimension) Matrix question (Only for Side by Side Matrix question)
answers This is a JSON array of answers
Parameters for "answers" array
Parameter Description
id This is an answer ID
text This is an answer text
index This is an index of the answer in the answer array
percent This gives the percentage of answer's selection
count This is number of times the answer is selected
Response (Output) JSON Example:
                {
                "response":{
                "surveyID":3981
                "surveyName":"Test Survey"
                "viewedCount":184,
                "dropOutCount":118,
                "startedCount":127,
                "terminatedCount":0,
                "completionRate":"7.09%",
                "averageTimeInSeconds":"38",
                "completeCount":9,
                "surveyStatistics":[
                {
                "sectionID":1,
                "description":"How satisfied are you with the following:",
                "type":"B"
                "questions":[
                {
                "id":17598515,
                "text":"McDonalds",
                "answers":[
                {
                "id":69126,
                "text":"Very Unsatisfied",
                "index":1
                "percent":"12.5",
                "count":1
                },
                {
                "id":69127,
                "text":"Unsatisfied",
                "index":2
                "percent":"0",
                "count":0
                },
                {
                "id":69128,
                "text":"Neutral",
                "index":3
                "percent":"50",
                "count":4
                },
                {
                "id":69129,
                "text":"Satisfied",
                "index":4
                "percent":"0",
                "count":0
                },
                {
                "id":69130,
                "text":"Very Satisfied",
                "index":5
                "percent":"25",
                "count":2
                },
                {
                "id":71258,
                "text":"N/A",
                "index":6
                "percent":"12.5",
                "count":1
                }
                ]
                },
                {
                "id":17598516,
                "text":"Cafe Coffee Day",
                "answers":[
                {
                "id":69131,
                "text":"Very Unsatisfied",
                "index":1
                "percent":"0",
                "count":0
                },
                {
                "id":69132,
                "text":"Unsatisfied",
                "index":2
                "percent":"28.57",
                "count":2
                },
                {
                "id":69133,
                "text":"Neutral",
                "index":3
                "percent":"28.57",
                "count":2
                },
                {
                "id":69134,
                "text":"Satisfied",
                "index":4
                "percent":"14.29",
                "count":1
                },
                {
                "id":69135,
                "text":"Very Satisfied",
                "index":5
                "percent":"28.57",
                "count":2
                },
                {
                "id":71259,
                "text":"N/A",
                "index":6
                "percent":"0",
                "count":0
                }
                ]
                },
                {
                "id":17598516,
                "text":"Starbucks",
                "answers":[
                {
                "id":69136,
                "text":"Very Unsatisfied",
                "index":1
                "percent":"0",
                "count":0
                },
                {
                "id":69137,
                "text":"Unsatisfied",
                "index":2
                "percent":"28.57",
                "count":2
                },
                {
                "id":69138,
                "text":"Neutral",
                "index":3
                "percent":"42.86",
                "count":3
                },
                {
                "id":69139,
                "text":"Satisfied",
                "index":4
                "percent":"14.29",
                "count":1
                },
                {
                "id":69140,
                "text":"Very Satisfied",
                "index":5
                "percent":"14.29",
                "count":1
                },
                {
                "id":71260,
                "text":"N/A",
                "index":6
                "percent":"0",
                "count":0
                }
                ]
                }
                ]
                },
                {
                "sectionID":2,
                "description":"How often do you conduct surveys?",
                "type":"U",
                "questions":[
                {
                "id":17598984,
                "text":"How often do you conduct surveys?"
                "answers":[
                {
                "id":71267,
                "text":"Weekly",
                "index":1,
                "percent":"50",
                "count":2
                },
                {
                "id":71268,
                "text":"Monthly",
                "index":2,"
                "percent":"0",
                "count":0
                },
                {
                "id":71269,
                "text":"Quarterly",
                "index":3,
                "percent":"0",
                "count":0
                },
                {
                "id":71270,
                "text":"Annually",
                "index":4,
                "percent":"50",
                "count":2
                },
                {
                "id":71321,
                "text":"Other",
                "index":5,
                "percent":"0",
                "count":0
                }
                ]
                }
                ]
                },
                {
                "sectionID":3,
                "type":"D",
                "description":[
                    {
                    "subHeading":["Not Important",
                    "Very Important"],
                    "title":"Importance",
                    "mdmSectionNum":0
                    }
                    ,
                    {
                    "subHeading":["Not Satisfied",
                    "Very Satisfied"],
                    "title":"Satisfaction",
                    "mdmSectionNum":1
                    }
                    ],
                "questions":[
                {
                "id":17599138,
                "text":"Customer Service",
                "answers":[
                {
                "id":71938,
                "text":"1",
                "index":1,
                "percent":"0",
                "count":0
                },
                {
                "id":71939,
                "text":"2",
                "index":2,
                "percent":"50",
                "count":1
                },
                {
                "id":71940,
                "text":"3",
                "index":3,
                "percent":"50",
                "count":1
                },
                {
                "id":71941,
                "text":"4",
                "index":4,
                "percent":"0",
                "count":0
                },
                {
                "id":71942,
                "text":"5",
                "index":5,
                "percent":"0",
                "count":0
                }
                ],
                "mdmSectionNum":0
                },
                {
                "id":17599141,
                "text":"Customer Service",
                "answers":[
                {
                "id":71953,
                "text":"1",
                "index":1,
                "percent":"0",
                "count":0
                },
                {
                "id":71954,
                "text":"2",
                "index":2,
                "percent":"0",
                "count":0
                },
                {
                "id":71955,
                "text":"3",
                "index":3,
                "percent":"0",
                "count":0
                },
                {
                "id":71956,
                "text":"4",
                "index":4,
                "percent":"100",
                "count":2
                },
                {
                "id":71957,
                "text":"5",
                "index":5,
                "percent":"0",
                "count":0
                }
                ],
                "mdmSectionNum":1
                },
                {
                "id":17599139,
                "text":"Product Packaging",
                "answers":[
                {
                "id":71943,
                "text":"1",
                "index":1,
                "percent":"0",
                "count":0
                },
                {
                "id":71944,
                "text":"2",
                "index":2,
                "percent":"0",
                "count":0
                },
                {
                "id":71945,
                "text":"3",
                "index":3,
                "percent":"50",
                "count":1
                },
                {
                "id":71946,
                "text":"4",
                "index":4,
                "percent":"50",
                "count":1
                },
                {
                "id":71947,
                "text":"5",
                "index":5,
                "percent":"0",
                "count":0
                }
                ],
                "mdmSectionNum":0
                },
                {
                "id":17599142,
                "text":"Product Packaging",
                "answers":[
                {
                "id":71958,
                "text":"1",
                "index":1,
                "percent":"0",
                "count":0
                }
                ,
                {
                "id":71959,
                "text":"2",
                "index":2,
                "percent":"0",
                "count":0
                }
                ,
                {
                "id":71960,
                "text":"3",
                "index":3,
                "percent":"100",
                "count":2
                }
                ,
                {
                "id":71961,
                "text":"4",
                "index":4,
                "percent":"0",
                "count":0
                }
                ,
                {
                "id":71962,
                "text":"5",
                "index":5,
                "percent":"0",
                "count":0
                }
                ],
                "mdmSectionNum":1
                }
                ,
                {
                "id":17599140,
                "text":"On-Time Arrival",
                "answers":[
                {
                "id":71948,
                "text":"1",
                "index":1,
                "percent":"0",
                "count":0
                }
                ,
                {
                "id":71949,
                "text":"2",
                "index":2,
                "percent":"0",
                "count":0
                }
                ,
                {
                "id":71950,
                "text":"3",
                "index":3,
                "percent":"0",
                "count":0
                }
                ,
                {
                "id":71951,
                "text":"4",
                "index":4,
                "percent":"50",
                "count":1
                }
                ,
                {
                "id":71952,
                "text":"5",
                "index":5,
                "percent":"50",
                "count":1
                }
                ],
                "mdmSectionNum":0
                }
                ,
                {
                "id":17599143,
                "text":"On-Time Arrival",
                "answers":[
                {
                "id":71963,
                "text":"1",
                "index":1,
                "percent":"0",
                "count":0
                }
                ,
                {
                "id":71964,
                "text":"2",
                "index":2,
                "percent":"50",
                "count":1
                }
                ,
                {
                "id":71965,
                "text":"3",
                "index":3,
                "percent":"0",
                "count":0
                }
                ,
                {
                "id":71966,
                "text":"4",
                "index":4,
                "percent":"0",
                "count":0
                }
                ,
                {
                "id":71967,
                "text":"5",
                "index":5,
                "percent":"50",
                "count":1
                }
                ],
                "mdmSectionNum":1
                }
                ],
                }
                }
                ]
                },
                "status":
                {
                "message":"OK",
                "id":200,
                "method":"surveyanalytics.survey.surveyStatistics",
                "serverUTC":1374484093534,
                "url":"/a/api/surveyanalytics.survey.surveyStatistics",
                "apiKey":"77407dc0-9c05-4d5d-afe6-1d65c15ada64"
                }
                }
            

Sample Java Code:

                import java.util.*;

                import org.apache.http.client.ResponseHandler;
                import org.apache.http.client.methods.HttpPost;
                import org.apache.http.entity.StringEntity;
                import org.apache.http.impl.client.BasicResponseHandler;
                import org.apache.http.impl.client.DefaultHttpClient;
                import org.json.JSONArray;
                import org.json.JSONException;
                import org.json.JSONObject;

                public class SurveyAnalyticsAPIExample {
                    public static final String API_KEY = "77407dc0-9c05-4d5d-afe6-1d65c15ada64";
                    public static final String DEVICE_KEY = "lbeud";
                    public static final String API_URL = "http://api.surveyanalytics.com/a/api/";
                    public static final String RESPONSE_COUNT_METHOD_NAME = "surveyanalytics.survey.responseCount";
                    public static final String SURVEY_RESPONSES_METHOD_NAME = "surveyanalytics.survey.surveyResponses";
                    public long surveyID = 3643;

                    public long getCompletedResponseCount() throws Exception {
                        String path = API_URL + RESPONSE_COUNT_METHOD_NAME + "?apiKey=" + API_KEY + "&deviceKey=" + DEVICE_KEY;
                        DefaultHttpClient httpclient = new DefaultHttpClient();
                        HttpPost httpost = new HttpPost(path);
                        String data = "{"id":"" + surveyID + "","resultMode":"0"}";
                        StringEntity se = new StringEntity(data);
                        httpost.setEntity(se);
                        httpost.setHeader("Accept", "application/json");
                        httpost.setHeader("Content-type", "application/json");
                        ResponseHandler responseHandler = new BasicResponseHandler();
                        Object resp = httpclient.execute(httpost, responseHandler);
                        String json =  resp.toString();
                        JSONObject obj = new JSONObject(json);
                        obj = obj.getJSONObject("response");
                        return Long.parseLong(obj.getString("completeCount"));
                    }

                    public String getResponses(int startingResponseCounter) throws Exception {
                        String path = API_URL + SURVEY_RESPONSES_METHOD_NAME + "?apiKey=" + API_KEY + "&deviceKey=" + DEVICE_KEY;
                        DefaultHttpClient httpclient = new DefaultHttpClient();
                        HttpPost httpost = new HttpPost(path);
                        String data = "{"id":"" + surveyID + "","resultMode":"0","startingResponseCounter":""+ startingResponseCounter +""}";
                        StringEntity se = new StringEntity(data);
                        httpost.setEntity(se);
                        httpost.setHeader("Accept", "application/json");
                        httpost.setHeader("Content-type", "application/json");
                        ResponseHandler responseHandler = new BasicResponseHandler();
                        Object resp = httpclient.execute(httpost, responseHandler);
                        return resp.toString();
                    }

                    public void printResponses() throws Exception {
                        long totalResponses = getCompletedResponseCount();
                        System.out.println("Completed Response Count is: " + totalResponses);

                        String responsesJson = getResponses(0);
                        JSONObject jr = new JSONObject(responsesJson);
                        jr = jr.getJSONObject("response");

                        JSONArray metaData = jr.getJSONArray("metaData");
                        Map questionMap = getQuestionMap(metaData);

                        JSONArray responses = jr.getJSONArray("responses");
                        for (int j=0;j < responses.length();j++) {
                            JSONObject response = (JSONObject)responses.get(j);

                            System.out.println("RESPONSE ID : " + response.getLong("responseID"));
                            System.out.println("Time Taken : " + response.getInt("timeTaken"));
                            System.out.println("Timestamp : " + response.getString("timestamp"));
                            if (response.has("ipAddress")) {
                                System.out.println("IP Address : " + response.getString("ipAddress"));
                            }

                            JSONArray customVariables = response.getJSONArray("customVariables");
                            for (int k=0; k < customVariables.length(); k++) {
                                JSONObject customVarResult = customVariables.getJSONObject(k);
                                System.out.print("Custom" + customVarResult.getInt("index") + " Value: " + customVarResult.getString("value"));
                            }

                            JSONArray results = response.getJSONArray("results");
                            //Print result for each question one by one
                            Iterator it = questionMap.values().iterator();
                            while (it.hasNext()) {
                                Question question = (Question)it.next();
                                List values = filterResponse(question, results);
                                System.out.println((j+1) + ". Question ID: " + question.questionID);
                                System.out.println((j+1) + ". Question Text: " + question.questionText);
                                System.out.print((j+1) + ". Results: ");
                                if (values.size() == 0) {
                                    System.out.println("Not Answered.");
                                }
                                for (int i=0; i < values.size(); i++) {
                                    AnswerResponse aR = (AnswerResponse)values.get(i);
                                    Answer a = (Answer)question.answerMap.get(String.valueOf(aR.index));
                                    System.out.print((i+1) + ". index=" + aR.index + (aR.text != null ? ", text= " + aR.text : ""));
                                    if (aR.rank > 0) {
                                        System.out.print(", Rank=" + aR.rank);
                                    }
                                    if (a.isOther) {
                                        System.out.print(", Is Other Type: true");
                                    }
                                    if (a.isDynamicText) {
                                        System.out.print(", Is Dynamic Text: true");
                                    }
                                    //if you want answer Text instead of index
                                    System.out.println("Answer Text=" + a.answerText);
                                }
                            }
                        }
                    }

                    private class Question {
                        public long questionID;
                        public String questionText;
                        public boolean hasRank = false;
                        Map answerMap = new HashMap();
                    }

                    private class Answer {
                        public int index;
                        public boolean isOther = false;
                        public boolean isDynamicText = false;
                        public String answerText;
                    }

                    private class AnswerResponse {
                        public int index = -1;
                        public String text;
                        public int rank = -1;
                    }

                    public Map getQuestionMap(JSONArray metaData) throws JSONException {
                        Map questions = new HashMap();
                        for (int i=0; i < metaData.length(); i++) {
                            JSONObject obj = metaData.getJSONObject(i);
                            Question question = new Question();
                            question.questionID = obj.getLong("questionID");
                            question.questionText = obj.getString("questionText");
                            //for rank type question
                            if (obj.has("hasRank")) {
                                question.hasRank = true;
                            }
                            JSONArray answers = obj.getJSONArray("answers");
                            for (int j=0; j < answers.length(); j++) {
                                JSONObject aObj = answers.getJSONObject(j);
                                Answer answer = new Answer();
                                answer.index = aObj.getInt("index");
                                answer.answerText = aObj.getString("answerText");
                                if (aObj.has("dynamicText")) {
                                    answer.isDynamicText = true;
                                }
                                if (aObj.has("other")) {
                                    answer.isOther = true;
                                }
                                question.answerMap.put(String.valueOf(answer.index), answer);
                            }
                            questions.put(String.valueOf(question.questionID), question);
                        }
                        return questions;
                    }

                    public List filterResponse(Question question, JSONArray questionResults) throws JSONException {
                        List values = new ArrayList();
                        for (int i=0; i < questionResults.length(); i++) {
                            JSONObject result = questionResults.getJSONObject(i);
                            if (result.getString("questionID").equals(String.valueOf(question.questionID))) {
                                AnswerResponse answerResponse = new AnswerResponse();
                                answerResponse.index = result.getInt("index");
                                if (result.has("text")) {
                                    answerResponse.text = result.getString("text");
                                }
                                if (result.has("rank")) {
                                    answerResponse.rank = result.getInt("rank");
                                }
                                values.add(answerResponse);
                            }
                        }
                        return values;
                    }
                }
            

War dieser Artikel hilfreich?
Das tut uns leid
Wie können wir es verbessern?
einreichen

Das könnte Sie auch noch interessieren...