1

I tried to parse a Json response I guet from my limesurvey server to Java, however I don't see what type of Class I should create it.

Here is the json string that I want to parse into a java object :

{"id":1,"result":{"gid":"1","type":"L","help":"Veuillez entrer votre niveau d'\u00e9tudes \u00e0 l'INPT.","language":"fr","sid":"796246","question_order":"3","question":"<p>\r\n\tvotre niveau d'\u00e9tudes \u00e0 l'INPT :<\/p>\r\n","answeroptions":{"A1":{"answer":"INE1","assessment_value":"0","scale_id":"0"},"A2":{"answer":"INE2","assessment_value":"1","scale_id":"0"},"A3":{"answer":"INE3","assessment_value":"1","scale_id":"0"}}},"error":null}

In order to parse it I created the following classes :

   public class Answer 
{
    String answer;
    int assessment_value;
    int scale_id;

    @Override
    public String toString() {
        return "answer : "+answer + " - assessment_value : " + assessment_value + " - scale_id :" + scale_id;
    }

}
public class answerOptions 
{
    String a;
    Answer t;

}
public class QuestionProperties 
{
    int gid;
    String type;
    String help;
    String language;
    int sid;
    int question_order;
    String question;
    ArrayList<answerOptions> answeroptions;

    @Override
    public String toString() {
        return "gid : "+gid + " - type : " + type + " - help :" + help + " - language :" + language + " - sid :" + sid + " - question_order :" + question_order + " - question :" + question;
    }
}
public class getQuestionProperties 
{
    int id;
    QuestionProperties result;
    String error;

    @Override
    public String toString() {
        return "id : "+id + " - result : " + result + " - error :" + error;
    }

}

The problem I have is that I declared "answeroptions" as an array while it is not, however I can't know for sure the number of options in there, I tried a class that works like a pair of a sort but it's not working ?? any ideas on how to model this problem without loosing genrality since I want a method to automatically parse this whatever the number of options !!

1 Answers1

0

You are almost doing well. Just change it to Map<String,Answer> instead of ArrayList<answerOptions> as per the JSON string. Here "A1", "A2" and "A3" are keys of the Map.

sample:

class QuestionProperties {
    ...
    Map<String,Answer> answeroptions;
}

In JSON String anything enclosing inside

{...} is converted to Map or custom POJO class Object

[...] is converted to ArrayList

Learn more... about JSON and follow this post

enter image description here

enter image description here

Note: Follow Java Naming convention for class name. Encapsulate all variables by making private and use proper getter/setter methods.

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76