Stan Malcolm
Stan Malcolm

Reputation: 2790

Object inside object with retrofit

i need to send @Body like next:

{
  "test": "test",
  "test2": {
       "test2": "test2",
       "test2": "test2",
  },
  "test3": {
       "test3": "test3",
       "test3": "test3",
  },
}

I am new with retrofit, I know how to create simple @Body object, but how create objects inside object - I have no idea.

will be glad any help!

Upvotes: 2

Views: 1823

Answers (1)

maciekjanusz
maciekjanusz

Reputation: 4775

Just create classes for these inner objects, and aggregate them into one object:

class TestWrapper {

    @Expose
    String test;

    @Expose
    Test2 test2;

    @Expose
    Test3 test3;
}

class Test2 {

    @SerializedName("something_name") // <- this will be the JSON key name
    @Expose
    String something;

    @SerializedName("something_else_name")
    @Expose
    String somethingElse;
}

etc. Then pass the TestWrapper object as the request @Body. Also, not that in your JSON you named two objects the same ("test2", "test3") - you can't do it, keys must be unique. Annotations in this code are the GSON library annotations: @Expose and @SerializedName

Upvotes: 3

Related Questions