【问题标题】:Create Dynamic Object Request In Retrofit在改造中创建动态对象请求
【发布时间】:2019-09-21 05:34:33
【问题描述】:

如何为改造请求创建动态对象。例如 示例请求 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"
        }
      ]
    }
  ]
}

【问题讨论】:

  • 我们可以在这里使用通用对象。你试过了吗?
  • @TheAnkush 使用 TreeMap 解决了它,然后将 TreeMap 的键视为参数名,将值视为值。感谢您的回复

标签: android web-services retrofit


【解决方案1】:

使用 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);

【讨论】:

    猜你喜欢
    • 2020-10-11
    • 2017-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    • 1970-01-01
    • 2020-07-05
    • 1970-01-01
    相关资源
    最近更新 更多