简体   繁体   中英

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

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

converts into object by 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
//]

and I want to get rid of the 3rd item. Is it possible to do it AFTER it has been converted to object? Or can it only be done when it's String / InputStream ? And how can I do that?

Thanks!

Edit: clarify that the constructor works, but gson failed to understand kotlin rules and injected objects that I can't check in Kotlin

If you don't like empty objects then just remove them. You should always can do it after parsing. However please be aware that in Kotlin lists can be mutable or not. It you received an inmutable one (built with "listOf") then you will have to build a new list including only the elements you want.

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

Edited: Ok, I understand you can't even parse the json in first place. In this case maybe you can try this:

  1. To allow nulls: change type of compulsory_field from Int to Int? at declaration
  2. Fix your json string before parsing: In your case you can replace all {} with {"compulsory_field": null}
  3. Now gson parser should obtain a valid list.

I came up with a ugly "solution"/workaround, but I am still searching for a better answer (or get the project to switch to moshi codegen or something else, whichever comes first)

Basically I just copy each object again to make sure it goes through all the null-safety checking kotlin provides

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
  }
}

Now the fixedSomethingList should be clean. Again, very hacky, but it works......

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM