改进身体注释数据

时间:2017-03-21 12:55:28

标签: android post annotations retrofit

我正在使用Retrofit库@Body注释,

创建了一个界面:

interface Foo {

  @POST("/jayson")
  FooResponse postJson(@Body FooRequest body);

}

创建了一个模型类:

public class FooRequest {
  final String foo;
  final String bar;

  FooRequest(String foo, String bar) {
    this.foo = foo;
    this.bar = bar;
  }
}

创建了一个请求:

FooResponse = foo.postJson(new FooRequest("kit", "kat"));

然后我收到回复:

{
    "foo": "kit",
    "bar": "kat"
}

但是如果我想创建这样的响应怎么办:

{
    "foo": "kit",
    "bar": "kat",
    "obj": { 
        "id": "1"
    }
}

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:0)

您必须创建表示嵌入式响应字段的类字段:

class Embedded {
    final String id;
}

// The whole response
public class FooRequest {
  final String foo;
  final String bar;
  final Embedded obj;

  FooRequest(String foo, String bar, Embedded obj) {
    this.foo = foo;
    this.bar = bar;
    this.obj = obj;
  }
}

这将被序列化为JSON:

{
    "foo": "kit",
    "bar": "kat",
    "obj": {
        "id": "1"
    }
}

答案 1 :(得分:0)

public class FooRequest {
  final String foo;
  final String bar;
  final Class object;

  FooRequest(String foo, String bar, Class object) {
    this.foo = foo;
    this.bar = bar;
    this.object = object;
  }
}

将Class.java创建为:

public class Class
{
int id;

//setter getters for id
}

FooResponse = foo.postJson(new FooRequest("kit", "kat", class));

其中class是您设置的对象。