簡體   English   中英

如何找到Gson生成的無效Kotlin對象(從反射)?

[英]How to find invalid Kotlin object generated by Gson (from reflection)?

{
  "data":[{"compulsory_field": 1}, {"compulsory_field": 2}, {}]
}

通過gson轉換為對象

data class Something(val compulsory_field: Int)

val somethingList = //gson parse the data
println(somethingList)

//[
//    Something(compulsory_field = 1),
//    Something(compulsory_field = 2),
//    Something(compulsory_field = null)    //Should not exists
//]

我想擺脫第三項。 將其轉換為對象之后,是否可以這樣做? 還是只能在String / InputStream 我該怎么辦?

謝謝!

編輯:澄清構造函數的工作,但gson無法理解kotlin規則並注入了我無法在Kotlin中檢查的對象

如果您不喜歡空的物體,則將其移除。 解析后,您應該總是可以做到的。 但是請注意,在Kotlin中,列表是可變的還是不可變的。 如果您收到一個不變的列表(使用“ listOf”構建),則您將必須構建一個僅包含所需元素的新列表。

https://kotlinlang.org/docs/reference/collections.html

編輯:好的,我知道您甚至無法解析json。 在這種情況下,您可以嘗試以下操作:

  1. 要允許空值:將compulsory_field的類型從Int更改為Int? 申報時
  2. 解析前修復您的json字符串:您可以將所有{}替換為{“ compulsory_field”:null}
  3. 現在,gson解析器應該獲取有效列表。

我提出了一個難看的“解決方案” /解決方法,但我仍在尋找更好的答案(或讓項目切換到moshi codegen或其他,以先到者為准)

基本上,我只是再次復制每個對象,以確保它通過了kotlin提供的所有null安全檢查

val somethingList = //gson parse the data
val fixedSomethingList = somethingList.mapNotNull {
    try {
    it.copy(compulsory_field = it.compulsory_field)
  } catch (e: IllegalArgumentException) { //if gson inserted a null to a non-null field, this will make it surface
    null  //set it to null so that they can be remove by mapNotNull above
  }
}

現在, fixedSomethingList應該是干凈的。 再次,非常hacky,但是可以用……

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM