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

Android使用Retrofit向Web Service发送JSON:嵌套数组配置求助

在Android中使用Retrofit发送包含JSON数组的请求解决方案

别担心,我帮你搞定这个问题!核心思路是把你要发送的JSON结构转换成对应的数据模型类,然后通过Retrofit的@Body注解传递整个对象就可以了,下面一步步来操作:

1. 创建对应的数据模型类

首先把你给出的JSON拆成两个数据类:一个是包含所有顶层字段的主请求类(比如叫OrderRequest),另一个是ItemList数组里的子项类(OrderItem)。用Kotlin的写法如下,Java写法类似,只需补充getter/setter或用Lombok简化:

import com.google.gson.annotations.SerializedName

// 主请求类,对应顶层JSON对象
data class OrderRequest(
    @SerializedName("Id") val id: String,
    @SerializedName("UnitName") val unitName: String,
    @SerializedName("UnitCount") val unitCount: String,
    @SerializedName("UnitAmount") val unitAmount: String,
    @SerializedName("CustomerId") val customerId: String,
    @SerializedName("PersonelId") val personelId: String,
    @SerializedName("CustomerCode") val customerCode: String,
    @SerializedName("OrderCode") val orderCode: String,
    @SerializedName("ItemList") val itemList: List<OrderItem>
)

// 子项类,对应ItemList数组里的单个对象
data class OrderItem(
    @SerializedName("StockId") val stockId: Int,
    @SerializedName("Count") val count: Int,
    @SerializedName("Amount") val amount: Int,
    @SerializedName("TotalAmount") val totalAmount: Int,
    @SerializedName("Discount1") val discount1: String,
    @SerializedName("Discount2") val discount2: String,
    @SerializedName("Discount3") val discount3: String,
    @SerializedName("Discount4") val discount4: String,
    @SerializedName("DiscountTotal") val discountTotal: String,
    @SerializedName("TaxPercent") val taxPercent: String,
    @SerializedName("TaxAmount") val taxAmount: String,
    @SerializedName("GrandTotal") val grandTotal: String
)

这里用@SerializedName是为了保证模型类字段名和JSON的key完全匹配,避免因大小写或命名风格差异导致序列化失败。

2. 配置Retrofit实例

先确保你在build.gradle(Module级别)里添加了Retrofit和Gson转换器的依赖:

// Retrofit核心库
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
// Gson转换器,用于自动序列化/反序列化JSON
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

然后创建Retrofit单例实例:

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

object RetrofitClient {
    // 替换成你的Web Service基础URL
    private const val BASE_URL = "https://your-api-domain.com/"

    val instance: ApiService by lazy {
        val retrofit = Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        retrofit.create(ApiService::class.java)
    }
}

3. 创建Retrofit接口

定义POST请求的接口,用@Body注解传递我们的OrderRequest对象:

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

interface ApiService {
    // 替换成你实际的接口路径
    @POST("orders/submit")
    // 如果不需要处理响应,可替换成Call<Void>
    fun sendOrder(@Body orderRequest: OrderRequest): Call<YourResponseModel>
    
    // 如果你用Kotlin协程,推荐改成suspend函数:
    // suspend fun sendOrder(@Body orderRequest: OrderRequest): YourResponseModel
}

这里的YourResponseModel是服务器返回响应对应的模型类,根据实际接口返回结构定义即可。

4. 发起请求示例

传统Callback方式

// 构建请求数据
val orderItem = OrderItem(
    stockId = 1,
    count = 1,
    amount = 1,
    totalAmount = 1,
    discount1 = "0",
    discount2 = "0",
    discount3 = "0",
    discount4 = "0",
    discountTotal = "0",
    taxPercent = "18",
    taxAmount = "1.18",
    grandTotal = "1.18"
)

val orderRequest = OrderRequest(
    id = "1",
    unitName = "-",
    unitCount = "1",
    unitAmount = "1",
    customerId = "206",
    personelId = "1",
    customerCode = "PERSONEL-007",
    orderCode = "147",
    itemList = listOf(orderItem)
)

// 发起请求
RetrofitClient.instance.sendOrder(orderRequest).enqueue(object : retrofit2.Callback<YourResponseModel> {
    override fun onResponse(call: Call<YourResponseModel>, response: retrofit2.Response<YourResponseModel>) {
        if (response.isSuccessful) {
            // 请求成功,处理服务器返回的响应
        } else {
            // 请求失败,可通过response.errorBody()查看错误信息
        }
    }

    override fun onFailure(call: Call<YourResponseModel>, t: Throwable) {
        // 网络异常,处理错误(比如无网络、超时等)
    }
})

Kotlin协程方式(推荐)

如果你的项目用了协程,可在ViewModel或CoroutineScope中发起请求:

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch

class OrderViewModel : ViewModel() {
    fun submitOrder() {
        viewModelScope.launch {
            try {
                val orderItem = OrderItem(/* 填充子项数据 */)
                val orderRequest = OrderRequest(/* 填充主请求数据 */)
                val response = RetrofitClient.instance.sendOrder(orderRequest)
                // 处理成功响应
            } catch (e: Exception) {
                // 处理异常(网络错误、接口报错等)
            }
        }
    }
}

这样配置后,Retrofit会自动把OrderRequest对象序列化成你需要的JSON格式,包括嵌套的ItemList数组,发送给服务器。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:48:40