在改造中序列化查询参数 [英] Serialize Query-Parameter in Retrofit

查看:93
本文介绍了在改造中序列化查询参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有以下要求:

pre $ @查询(配方)配方食谱,回调< String>回调);

我想要json(recipe),但不幸的是我的请求只是调用toString()配方根本不起作用。

我可以覆盖食谱中的toString,但我宁愿有一个通用的解决方案。



我不能使用@Body,因为我需要指定,我发送了什么(我需要有recipe = json(theRecipe)。



我也不能改变序列化来添加recipe =,因为我不负责服务器。



目前我正在使用QueryMap Map我放入了一个序列化的对象,尽管这样做很有效,但在我看来,这不是一个很好的解决方案。



我可以以某种方式拦截retrofit-adapter吗?

解决方案

我不认为它现在以一种很好的方式支持这个。请查看以下作者之一的答案: https://github.com/square/retrofit/issu es / 291



建议的方法是创建一个自定义类型来覆盖 toString()方法,因为Retrofit内部使用 String.valueOf(value)将查询或路径参数转换为字符串。

<所以,你可以有这样的东西:

  class Recipe {
public int id;
public String title;

@Override
public String toString(){
//如果您想要
,可以在这里使用GSON序列化//这不是一个强大的实现
return Integer.toString(id)+ - + title;
}
}


Imagine the following request:

@POST("/recipes/create")
void createRecipe(@Query("recipe") Recipe recipe, Callback<String> callback);

I would like to have toJson(recipe) but unfortunately my request is just calling toString() for my recipe which does not work at all.

I could override the toString inside of Recipe but I'd rather have a general solution.

I cannot use @Body as I need to specify, what I'm sending (i need to have "recipe=json(theRecipe)".

I also cannot change the serialization to add "recipe=" as I'm not in charge of the server.

At the moment I'm using a QueryMap Map where I put in a serialized object. Although this works, it's not a very nice solution in my opinion.

Can I somehow intercept the retrofit-adapter?

解决方案

I don't think it supports this right now in some nice way. Check this answer by one of the authors: https://github.com/square/retrofit/issues/291

The suggested method from that answer is to create a custom type that overrides the toString() method, because Retrofit internally uses String.valueOf(value) to convert query or path parameters to strings.

So, you could have something like this:

class Recipe {
  public int id;
  public String title;

  @Override
  public String toString() {
    // You can use a GSON serialization here if you want
    // This is not a robust implementation
    return Integer.toString(id) + "-" + title;
  }
}

这篇关于在改造中序列化查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆