You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Retrofit发送含复杂JSON数据的POST请求?

How to Send a Nested JSON POST Request with Retrofit

Hey there, sending a nested JSON body via Retrofit is totally straightforward once you map the JSON structure to proper data classes. Let's break this down into simple, actionable steps using both Kotlin and Java examples (pick whichever you're using!).

1. Define Data Classes (Model the Nested JSON)

Retrofit relies on a serializer (like Gson or Moshi) to convert your objects to JSON, so you need to create classes that mirror the exact structure of your request body. Start from the innermost nested objects and work your way out:

Kotlin Example

// Inner nested classes
data class PersonalInfo(
    val first_name: String,
    val last_name: String,
    val date_of_birth: String // Use Date/LocalDateTime with custom converter if needed (see note below)
)

data class AddressInfo(
    val address_1: String,
    val address_2: String,
    val city: String,
    val state: String,
    val zip_code: String
)

data class ContactInfo(
    val email: String,
    val telephone: String,
    val telephone_type_id: Int
)

data class EmploymentInfo(
    val employer_name: String // Add other employment fields as required
)

// Top-level user object containing all nested info
data class User(
    val personal_info: PersonalInfo,
    val address_info: AddressInfo,
    val contact_info: ContactInfo,
    val employment_info: EmploymentInfo
)

// Root request body that matches the outer {"user": ...} structure
data class UserRequest(
    val user: User
)

Java Example

// Inner classes (make them static if nested, or use top-level classes)
public class PersonalInfo {
    private String first_name;
    private String last_name;
    private String date_of_birth;

    // Constructor, getters, and setters (use Lombok to reduce boilerplate if you want)
    public PersonalInfo(String first_name, String last_name, String date_of_birth) {
        this.first_name = first_name;
        this.last_name = last_name;
        this.date_of_birth = date_of_birth;
    }

    // Add getters and setters here
}

public class AddressInfo {
    private String address_1;
    private String address_2;
    private String city;
    private String state;
    private String zip_code;

    // Constructor, getters, setters
}

public class ContactInfo {
    private String email;
    private String telephone;
    private int telephone_type_id;

    // Constructor, getters, setters
}

public class EmploymentInfo {
    private String employer_name;

    // Constructor, getters, setters
}

public class User {
    private PersonalInfo personal_info;
    private AddressInfo address_info;
    private ContactInfo contact_info;
    private EmploymentInfo employment_info;

    // Constructor, getters, setters
}

public class UserRequest {
    private User user;

    public UserRequest(User user) {
        this.user = user;
    }

    // Getters and setters
}

Note about date handling: If you want to use a Date or LocalDateTime type instead of String for date_of_birth, configure your serializer to handle the custom format. For Gson, add this to your builder:

val gson = GsonBuilder()
    .setDateFormat("yyyy-MM-dd HH:mm:ss z")
    .create()

2. Create the Retrofit Service Interface

Define your POST endpoint in an interface, using the @Body annotation to pass your request object:

Kotlin

import retrofit2.http.Body
import retrofit2.http.POST

interface UserService {
    @POST("users/create") // Replace with your actual API endpoint path
    suspend fun createUser(@Body request: UserRequest): retrofit2.Response<YourResponseModel> // Replace with your API's response type
}

Java

import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.POST;

public interface UserService {
    @POST("users/create")
    Call<YourResponseModel> createUser(@Body UserRequest request);
}

3. Set Up the Retrofit Instance

Initialize Retrofit with your API's base URL and the converter factory for JSON serialization:

Kotlin

import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

val retrofit = Retrofit.Builder()
    .baseUrl("https://your-api-base-url.com/") // Replace with your API's base URL
    .addConverterFactory(GsonConverterFactory.create(gson)) // Use the custom Gson instance if you configured date handling
    .build()

val userService = retrofit.create(UserService::class.java)

Java

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://your-api-base-url.com/")
    .addConverterFactory(GsonConverterFactory.create(gson)) // Pass custom Gson if needed
    .build();

UserService userService = retrofit.create(UserService.class);

4. Execute the Request

Kotlin (Using Coroutines for Async Calls)

Run this in a coroutine scope (like a ViewModel or dedicated CoroutineScope):

CoroutineScope(Dispatchers.IO).launch {
    try {
        // Build your nested request objects step by step
        val personalInfo = PersonalInfo("Walter", "White", "1972-01-03 00:00:00 PST")
        val addressInfo = AddressInfo("308 NEGRA ARROYO LANE", "#", "ALBUQUERQUE", "NM", "87104")
        val contactInfo = ContactInfo("wwhite@test.com", "88888888888", 1)
        val employmentInfo = EmploymentInfo("Your Employer Name")
        val user = User(personalInfo, addressInfo, contactInfo, employmentInfo)
        val request = UserRequest(user)

        val response = userService.createUser(request)
        if (response.isSuccessful) {
            // Handle success: access the response body
            val result = response.body()
            // Do something with the result
        } else {
            // Handle error: get error details
            val errorMsg = response.errorBody()?.string()
            // Log or display the error
        }
    } catch (e: Exception) {
        // Handle network exceptions (e.g., no internet)
        e.printStackTrace()
    }
}

Java (Using Callback for Async Calls)

// Build the request object
PersonalInfo personalInfo = new PersonalInfo("Walter", "White", "1972-01-03 00:00:00 PST");
AddressInfo addressInfo = new AddressInfo("308 NEGRA ARROYO LANE", "#", "ALBUQUERQUE", "NM", "87104");
ContactInfo contactInfo = new ContactInfo("wwhite@test.com", "88888888888", 1);
EmploymentInfo employmentInfo = new EmploymentInfo("Your Employer Name");
User user = new User(personalInfo, addressInfo, contactInfo, employmentInfo);
UserRequest request = new UserRequest(user);

// Execute the call asynchronously
Call<YourResponseModel> call = userService.createUser(request);
call.enqueue(new Callback<YourResponseModel>() {
    @Override
    public void onResponse(Call<YourResponseModel> call, Response<YourResponseModel> response) {
        if (response.isSuccessful()) {
            YourResponseModel result = response.body();
            // Handle success
        } else {
            // Handle error
            try {
                String errorMsg = response.errorBody().string();
                // Log error details
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onFailure(Call<YourResponseModel> call, Throwable t) {
        // Handle network failure
        t.printStackTrace();
    }
});

内容的提问来源于stack exchange,提问作者Developer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:33:26