简体   繁体   English

如何使用Square的改进将多维哈希作为查询参数传递

[英]How to pass a multidimensional hash as query parameters using retrofit by Square

I have a map of string id's and points, from which I need to generate a path similar to this: 我有一个字符串id和点的映射,我需要从中生成类似于此的路径:

.../?assessment[id_1][points]=3&assessment[id_2][points]=5

I'm not exactly sure how i would do something like this in retrofit. 我不确定如何在改造中做这样的事情。 I've tried manually generating a string and appending it to the end of a request 我已经尝试手动生成一个字符串并将其附加到请求的末尾

@PUT("/path/to/api/{assessment}?{}")
    void postScore(@Path("assessment") String rubricAssessment, Callback<Submission> callback);

Which is pretty hacky and results in the error. 这是非常hacky并导致错误。

java.lang.IllegalArgumentException: Inteface.postScore: URL query string "{assessment}" must not have replace block.

Could someone suggest a better method of accomplishing this in retrofit? 有人可以建议一种更好的方法来改造吗?

Thank you for reading my question. 感谢您阅读我的问题。

EDIT: 编辑:

One possible solution i've found is to use either a QueryMap or a FieldMap, but that still requires me to create a helper method to manually construct each key value. 我发现一个可能的解决方案是使用QueryMap或FieldMap,但仍然需要我创建一个辅助方法来手动构建每个键值。 Something like this: 像这样的东西:

 private static String getFieldMap(Map<String,String> map){
    Map<String, String> fieldMap = new HashMap<String, String>();
    for (Map.Entry<String, String> entry : map.entrySet())) {
        map.put("assessment[" +entry.getCriterionId() +"][points]", String.valueOf(entry.getPoints()));
    }
    return fieldMap;
}

Then passing that map into something like this? 然后把那张地图传递给这样的东西?

 @put("/things")
 void things(@FieldMap Map<String, String> fields);
 }

Is that the best way to do this? 这是最好的方法吗? Any feedback is appreciated. 任何反馈都表示赞赏。

You are correct. 你是对的。 You can indeed use a QueryMap . 您确实可以使用QueryMap To be honest never tried using a FieldMap since QueryMap works perfectly fine for me. 说实话,从来没有尝试使用FieldMap因为QueryMap对我来说非常好。

If you want to use queryMap it is very simple. 如果你想使用queryMap,这很简单。 Example: 例:

Map testMap = new HashMap<String,String>();
    testMap.put("key1", "value1");
    testMap.put("key2", "value2");

And pass it to you postScore call. 并将它传递给你postScore call。

something.postScore("yourStringValue",testMap);

Your retrofit call should look something like this: 你的改装电话应该是这样的:

void postScore(@Path("assessment") String rubricAssessment, @QueryMap Map<String,String> callback)

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM