使用GSON解析NASA API JSON时,near_earth_objects数组返回空的解决方法
GSON解析NASA API数据时near_earth_objects数组返回null的修复方案
导致objet_one数组返回null的原因有三个,对应修复方法如下:
1. 根对象属性名不匹配
你的NasaResponse类中用neo对应JSON里的near_earth_objects字段,GSON无法自动映射,可通过两种方式修正:
方式一:直接修改属性名
class NasaResponse( val element_count: Int, val near_earth_objects: NearEarthObjects, // 改为和JSON字段名一致 val links: Links )
方式二:保留原属性名,添加注解
import com.google.gson.annotations.SerializedName class NasaResponse( val element_count: Int, @SerializedName("near_earth_objects") val neo: NearEarthObjects, val links: Links )
2. NearEarthObjects类属性名不匹配
你的near_earth_objects类中用objeto_uno对应JSON里的objet_one字段,同样需要修正:
方式一:修改属性名
class NearEarthObjects( val objet_one: ArrayList<NeoItem>, // 改为和JSON字段名一致 )
方式二:添加注解
import com.google.gson.annotations.SerializedName class NearEarthObjects( @SerializedName("objet_one") val objeto_uno: ArrayList<NeoItem>, )
3. 类型不匹配导致解析失败
JSON中id是字符串类型(比如"2465633"),但你的NeoItem类中把id定义为Int类型,GSON解析失败会导致整个数组为null,需要把id类型改为String:
data class NeoItem( val id: String, // 从Int改为String,匹配JSON类型 val name: String, val absolute_magnitude_h: Double, )
另外建议Kotlin类名首字母大写(比如links改为Links、near_earth_objects改为NearEarthObjects),符合编码规范。
修正后的完整解析示例:
val jsonToClass = gson.fromJson(nasaJson, NasaResponse::class.java) Log.d(TAG, "LINKS: ${jsonToClass?.links?.self}") Log.d(TAG, "COUNT: ${jsonToClass?.element_count}") // 现在可正常获取objet_one数组 jsonToClass?.near_earth_objects?.objet_one?.forEach { neoItem -> Log.d(TAG, "NEO ID: ${neoItem.id}, Name: ${neoItem.name}") }
内容的提问来源于stack exchange,提问作者Sergio76
相关产品推荐
相关产品推荐

