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

如何在JSON API数组中检查空对象?Jetpack Compose场景问题

问题:检查对象字段是否存在并显示对应文本

我尝试了多种方法,但仍未找到检查对象是否为空的可行方案。API返回的结构中,teamInfo对象有时不存在shortname字段,仅包含name和img字段。我希望当teamInfo中没有shortname时显示其他文本,目前尝试的代码如下:

Text(
    text = if(data.teamInfo[1].shortname != null){data.teamInfo[1].shortname}
    else{data.teams[1]},
    modifier = Modifier
        .weight(1f)
        .padding(5.dp)
        .align(Alignment.CenterVertically),
    fontWeight = FontWeight.Bold,
    maxLines = 1
)

解决方案

1. 用Elvis操作符简化空值判断

Elvis操作符?:可以直接替代if-else的空值逻辑,让代码更简洁:

Text(
    text = data.teamInfo[1].shortname ?: data.teams[1],
    modifier = Modifier
        .weight(1f)
        .padding(5.dp)
        .align(Alignment.CenterVertically),
    fontWeight = FontWeight.Bold,
    maxLines = 1
)

2. 避免数组越界异常

如果teamInfo的长度可能小于2(即索引1无对应元素),建议用getOrNull()替代直接索引访问,防止抛出IndexOutOfBoundsException:

Text(
    text = data.teamInfo.getOrNull(1)?.shortname ?: data.teams[1],
    modifier = Modifier
        .weight(1f)
        .padding(5.dp)
        .align(Alignment.CenterVertically),
    fontWeight = FontWeight.Bold,
    maxLines = 1
)

3. 确保数据类字段为可空类型

如果teamInfo对应的数据类中shortname未声明为可空类型(String?),需先修改数据类,否则字段不存在时解析会报错:

data class TeamInfo(
    val name: String,
    val img: String,
    val shortname: String? // 声明为可空类型
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 15:35:26