一句话说明

当 kotlin data class 和 gson 配合数据解析,val 字段会因为 json 数据中没有值而报空指针异常。
解决办法:

  • 给定一个默认值,比如 “”。
  • 或将字段类型改为 var,并且指定为可空类型。(当然,你就需要进行空判断了呀。)
  • 改用 Moshi 框架

如果你想知道为什么,我记得鸿洋写过一篇文章。

我给你找找…

找到了,点这里
Android避坑指南,Gson与Kotlin碰撞出一个不安全的操作

详细说明

没时间的,可以不往下看。

当你的数据格式是这样的。

  1. {
  2. "data": [
  3. {
  4. "id": "00000000000000000000000000000000",
  5. "name": "Default Department",
  6. "parentId": null,
  7. "nodeType": "1"
  8. },
  9. {
  10. "id": "ee7d951aeb98412aa4a421b2f3f16714",
  11. "name": "test1",
  12. "parentId": "00000000000000000000000000000000",
  13. "nodeType": "1"
  14. },
  15. {
  16. "id": "4d660402f2c847abae12c015cd2ecf0c",
  17. "name": "test2",
  18. "parentId": "00000000000000000000000000000000",
  19. "nodeType": "1"
  20. },
  21. {
  22. "id": "97150ce7a292449a8cacae413e3b68ca",
  23. "name": "123",
  24. "parentId": "00000000000000000000000000000000",
  25. "nodeType": "1"
  26. },
  27. {
  28. "id": "11111111111111111111111111111111",
  29. "name": "admin",
  30. "parentId": "00000000000000000000000000000000",
  31. "nodeType": "2"
  32. },
  33. {
  34. "id": "878a10e874d14fd9a15b18f4081c1ed8",
  35. "name": "TEST",
  36. "parentId": "4d660402f2c847abae12c015cd2ecf0c",
  37. "nodeType": "2"
  38. },
  39. {
  40. "id": "455d521c7e194f9fb414d9ff42d8e09e",
  41. "name": "wb",
  42. "parentId": "ee7d951aeb98412aa4a421b2f3f16714",
  43. "nodeType": "2"
  44. },
  45. {
  46. "id": "e9d1aae801164587978c3a9f17301549",
  47. "name": "WZY",
  48. "parentId": "4d660402f2c847abae12c015cd2ecf0c",
  49. "nodeType": "2"
  50. },
  51. {
  52. "id": "25c58da4ad634130abee0366c14969d1",
  53. "name": "zj",
  54. "parentId": "00000000000000000000000000000000",
  55. "nodeType": "2"
  56. },
  57. {
  58. "id": "24d6c7d98dbd49e69fa07f0e08cade54",
  59. "name": "ZJB",
  60. "parentId": "00000000000000000000000000000000",
  61. "nodeType": "2"
  62. },
  63. {
  64. "id": "54074775f5604408af1eb85fe88760b5",
  65. "name": "zs",
  66. "parentId": "ee7d951aeb98412aa4a421b2f3f16714",
  67. "nodeType": "2"
  68. },
  69. {
  70. "id": "bd4bd6a8ba634ac8b1ed6cbbf7343fc8",
  71. "name": "zyb",
  72. "parentId": "4d660402f2c847abae12c015cd2ecf0c",
  73. "nodeType": "2"
  74. }
  75. ]
  76. }

你就改成这样的 data class

data class RxResponseCandidates(val id: String, val name: String, var parentId: String?, val nodeType: String){
    fun isDept(): Boolean{
        // 1: 部门  2:员工
        return nodeType == "1"
    }
    fun isStaff(): Boolean{
        // 1: 部门  2:员工
        return nodeType == "2"
    }
    /// 是否没有父节点(是否是一级部门)
    fun hasNoParent(): Boolean{
        return parentId?.isEmpty() ?: false
    }
}

image.png

参考文章

[Moshi]认识新一代对Kotlin友好的JSON解析框架