根据要求改造 2 将对象转换为 Json

Retrofit 2 convert Object to Json on request

我有 class:

@XmlRootElement(name = "myobject")
@XmlAccessorType(XmlAccessType.FIELD)
public class MyObject {

    @XmlElement
    private Long id;
    @XmlElement
    private String name;
    ...
}

我使用 Retrofit 2 向服务器发送数据。要求

进入界面的方法:

@POST("/update")
Call<Response> updateObject(@Body MyObject myObject);

当我使用这个时:

retrofit = new Retrofit.Builder()
    .baseUrl(API_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .build();
ServerAPI api = getRetrofit().create(ServerAPI.class);
Call<Response> call = api.updateObject(myObject);
...
retrofit2.Response response = call.execute();
...

发送到服务器

{"id":3,"name"}

但我需要

{myobject:{"id":3,"name"}}

即将主体包裹在 {myobject} 中。如何修复?

最简单的做法是将您的响应包裹在您尝试发送的对象周围。

public class ObjectWrapper {
  @SerializedName("myobject")
  public final MyObject myObject;

  public ObjectWrapper(MyObject myObject) {
    this.myObject = myObject;
  }
}