JSON中的动态未知字段
Posted
技术标签:
【中文标题】JSON中的动态未知字段【英文标题】:Dynamic unknow field in JSON 【发布时间】:2020-02-29 12:54:13 【问题描述】:我正在尝试从以下 URL 构建正确的类:
https://api.nasa.gov/neo/rest/v1/feed?start_date=2020-01-01&end_date=2020-01-08&api_key=DEMO_KEY
此时,我的结构如下:
data class NearEarthObject (val asteroidObjects : Map<String, DateSelected>)
data class DateSelected (val date: ArrayList<Asteroid>)
data class Asteroid(
val id: Long,
val codename: String,
val closeApproachDate: String,
val absoluteMagnitude: Double,
val estimatedDiameter: Double,
val relativeVelocity: Double,
val distanceFromEarth: Double,
val isPotentiallyHazardous: Boolean
)
这是我的 Java 代码:
class MainActivity : AppCompatActivity()
val URLAPI = Constants.BASE_URL
override fun onCreate(savedInstanceState: Bundle?)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
asteroidActivityRv.layoutManager = LinearLayoutManager(this)
asteroidActivityRv.adapter = null
val retrofitAsteroids = Retrofit.Builder()
.baseUrl(URLAPI)
.addConverterFactory(GsonConverterFactory.create())
.build()
val apiAsteroid = retrofitAsteroids.create(ApiAsteroids::class.java)
val callAsteroid = apiAsteroid.getAsteroids()
callAsteroid.enqueue(object : Callback<NearEarthObject>
override fun onFailure(call: Call<NearEarthObject>?, t: Throwable?)
Log.e("TAG fail", t.toString())
override fun onResponse(
call: Call<NearEarthObject>,
response: Response<NearEarthObject>
)
for (res in response.body().asteroidObjects)
// Log.e("TAG result", res.value.date)
)
但我不断收到以下错误:
java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Set java.util.Map.entrySet()' on a null object reference
at com.example.nasanwsproject.MainActivity$onCreate$1.onResponse(MainActivity.kt:44)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
有人知道我做错了什么吗?
非常感谢您的帮助!
【问题讨论】:
【参考方案1】:看起来 response.body().asteroidObjects==null
我认为这个问题是因为你无法收到使用地图的响应。 它需要一个明确的类(包括字段和值。)
【讨论】:
以上是关于JSON中的动态未知字段的主要内容,如果未能解决你的问题,请参考以下文章