使用自定义表单键将POJO映射到application / x-www-form-urlencoded

时间:2014-07-25 02:12:49

标签: java mapping robospice spring-android

我使用RoboSpice和Spring Android来执行REST api调用。 需要将Content-Type设置为application / x-www-form-urlencoded发送数据。

我们说我有这样的Pojo课程:

public class Pojo {
  private String pojoAttribute;

  // getter + setter
}

这是我的请求类:

public class PojoRequest extends AbstractApiRequest<PojoResult> {

    private Pojo pojo;

    public PojoRequest(Pojo pojo) {
        super(PojoResult.class);
        this.pojo = pojo;
    }

    @Override
    public PojoResult loadDataFromNetwork() throws Exception {

        HttpEntity<Pojo> requestEntity = new HttpEntity<Pojo>(pojo, getDefaultHeaders());
        String url = buildUrlForPath("mypath");

        RestTemplate restTemplate = getRestTemplate();
        restTemplate.getMessageConverters().add(new FormHttpMessageConverter());

        return restTemplate.postForObject(url, requestEntity, PojoResult.class);
    }
}

所以,假设我需要发送这个身体:
pojo_attribute = FOO

现在我的代码不起作用,因为FormHttpMessageConverter不处理POJO。

我希望能做的是这样的事情:

public class Pojo {
  @FormProperty("pojo_attribute")
  private String pojoAttribute;

  // getter + setter
}

使用一个神奇的HttpMessageConverter将我的POJO转换为key = value格式,通过检查@FormProperty(不存在)注释将pojoAttribute转换为pojo_attribute,就像Jackson对@JsonProperty一样。

我的问题是:
- 是否可以使用现有的类/注释来执行此操作? - 还有另一种做类似事情的方法吗? - 如果我创建自己的HttpMessageConverter和一组注释来做这件事会不会有点过分?

0 个答案:

没有答案