Retrofit2:尝试将具有多个对象的对象作为Json发布?

时间:2017-11-16 09:37:53

标签: android retrofit2

我有类似的Content类;

公共类内容{

@SerializedName("id")
long id;
@SerializedName("content_type")
ContentType contentType;

long content_type_id;

@SerializedName("created_date")
Date createdDate;

@SerializedName("modified_date")
Date modifiedDate;

@SerializedName("components")
List<Component> components;

User owner;

这些User,Component和ContentType是我创建的类。我想把这个类转换成Json;

{
    "content_type": {
        "id": 1,
        "name": "Post",
        "components": [
            "text",
            "longtext",
            "video"
        ],
        "component_names": [
            "title",
            "body",
            "video"
        ]
    },
    "owner": {
        "url": "http://localhost:8000/users/1/",
        "id": 1,
        "username": "admin",
        "email": "admin@admin.com"
    },
    "owner_id": 1,
    "content_type_id": 1,
    "components": [
        {
            "component_type": "text",
            "order": 1,
            "type_data": {
                "data": "Amber Run - Found"
            }
        },
        {
            "component_type": "longtext",
            "order": 2,
            "type_data": {
                "data": "Warning sign"
            }
        },
        {
            "component_type": "video",
            "order": 3,
            "type_data": {
                "data": "https://www.youtube.com/watch?v=Yj6V_a1-EUA"
            }
        }
    ]
}

如果我使用PostMan发送这个原始Json数据,它就可以工作。

我在RetrofitApiService接口

中使用此方法
 @POST("group-contents/{group_id}/")
@FormUrlEncoded
Call<Content> postContent(@Path(value = "group_id", encoded = true)  long groupId, @Body Content content);

但是,我收到此错误

  

@Body参数不能与表单或多部分编码一起使用。

我应该如何正确使用改装来发送类似的Json对象?

1 个答案:

答案 0 :(得分:1)

您可以将其作为RequestBody发送,并且还必须删除@FormUrlEncoded

String json = new Gson().toJson(content) //Here content is your POJO class, that to be send.

RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);

@POST("group-contents/{group_id}/")
Call<Content> postContent(@Path(value = "group_id", encoded = true)  long groupId, @Body RequestBody body);