在改造中创建动态对象请求

时间:2019-05-02 16:37:38

标签: android web-services retrofit

如何为改装请求创建动态对象。例如 示例请求1:

 "answer" :     {
        "Aggravating factor" :         {
            "value_dropdown" : "None"
        },
        "Associated factors" :         {
            "value" : "1"
        }
}

示例请求2:

 "answer" :     {
            "Intensity :         {
                "value_dropdown" : "Major"
            },
            "Duration" :         {
                "value" : "5"
            }
    }

所以每次请求模型改变时, 我具有从答案表中收集的所有这些参数名和值  由最终用户填充,然后如何使用它来创建具有动态值(即“ answer”:{{“ parameter name”:“ value”}}}的请求模型。

我的努力: 带有序列化输出的静态模型:

public class SampleModel {


    @SerializedName("answer")
    public ArrayList<QuestionAnswers> answer;

    public SampleModel() {
        answer = new ArrayList<>();
    }


    public static class QuestionAnswers {
        public String question_title;
        public List<KeyValuePaire> questions;

        public QuestionAnswers() {
            questions = new ArrayList<>();
        }
    }

    public static class KeyValuePaire {
        public String _type;
        public String _value;
    }

}

此模型请求显示在日志下方:

{
  "answer": [
    {
      "question_title": "Aggravating factor",
      "questions": [
        {
          "_type": "value_dropdown",
          "_value": "None"
        }
      ]
    }
  ]
}

1 个答案:

答案 0 :(得分:3)

使用TreeMap解决它,然后将TreeMap的键视为参数名称,将值视为值。

public class RequestSelectedAnswers {

    @SerializedName("answer")
    TreeMap answers;

    public RequestSelectedAnswers() {
        answers = new TreeMap();
    }

    public TreeMap getAnswers() {
        return answers;
    }

    public void setAnswers(TreeMap answers) {
        this.answers = answers;
    }

}

并像这样使用它:

RequestSelectedAnswers request = new RequestSelectedAnswers();       
request.getAnswers().put("Intensity", someArrayOrAnotherMap);