Kotlin数据类用gson进行转换......而默认值是由零或null进行转换

hujrc8aj  于 2022-11-06  发布在  Kotlin
关注(0)|答案(3)|浏览(428)

我使用GSON来转换服务器返回的数据类。我这样定义数据类......并且有一些字段我不想用GSON转换......所以我添加了带注解的ExclusionStrategy。通过测试,我发现AnnotationExclusionStrategy运行正常,并且跳过了我不想转换的字段。我添加了带注解的字段,如uiType和testData。但实际上当我打印出对象时,我发现字段uiType和testData已经转换为零和null。
然后我创建了一个新的数据类。uiType和testData没有被擦除为零或空。GSON转换时出错了吗?
有没有办法解决这个问题
这是密码。

数据类实体:

  1. data class Product(@SerializedName("num_iid") var productId: Long,
  2. @SerializedName("title") var productName: String,
  3. @SerializedName("item_url") var productUrl: String,
  4. @SerializedName("pict_url") var productPic: String,
  5. @SerializedName("small_images") var productPics: ProductImageList,
  6. @SerializedName("zk_final_price") var productPrice: String,
  7. @SerializedName("reserve_price") var originPrice: String,
  8. @SerializedName("provcity") var place: String,
  9. @SerializedName("volume") var sellCount: String,
  10. @SerializedName("user_type") var sellerType: String,
  11. @SerializedName("nick") var sellerName: String,
  12. @SerializedName("seller_id") var sellerId: Long
  13. ) : MultiItemEntity {
  14. @Exclude
  15. @ShoppingCenterConstant.ProductListUiType
  16. var uiType = ShoppingCenterConstant.LIST_UI_TYPE_COMMON
  17. var testData = "TestData"
  18. override fun getItemType(): Int {
  19. return ShoppingCenterConstant.LIST_UI_TYPE_COMMON
  20. }
  21. override fun toString(): String {
  22. return "Product(productId=$productId, productName='$productName', productUrl='$productUrl', productPic='$productPic', productPics=$productPics, productPrice='$productPrice', originPrice='$originPrice', place='$place', sellCount='$sellCount', sellerType='$sellerType', sellerName='$sellerName', sellerId=$sellerId, uiType=$uiType, testData='$testData')"
  23. }
  24. }

GSON注解排除项:

  1. public class AnnotationExclusion implements ExclusionStrategy {
  2. public static final String TAG = GsonUtil.TAG;
  3. @Override
  4. public boolean shouldSkipField(FieldAttributes f) {
  5. boolean isShouldSkip = f.getAnnotation(Exclude.class) != null;
  6. return isShouldSkip;
  7. }
  8. @Override
  9. public boolean shouldSkipClass(Class<?> clazz) {
  10. boolean isShouldSkip = clazz.getAnnotation(Exclude.class) != null;
  11. return isShouldSkip;
  12. }

}

打印输出的位置:

  1. override fun showData(data: BaseListBean<Product>) {
  2. var product = Product(0, "", "", ""
  3. , ProductImageList(List(0, { String() })), "", "", "", ""
  4. , "", "", 0)
  5. LogUtils.info("print out new product:" + product)
  6. mResultListener.onResponse(data)
  7. }

使用GSON转换器得到的结果,* 您可以看到字段uiType和testData已转换为零或空值:*

  1. Product(productId=552634381786, productName='eoodoo新生儿礼盒婴儿衣服秋冬套装出生满月礼物初生母婴宝宝用品', productUrl='http://item.taobao.com/item.htm?id=552634381786', productPic='https://img.alicdn.com/tfscom/i4/2832303009/O1CN013tXM6L1Y6AFHSy7xN_!!0-item_pic.jpg', productPics=com.laka.ergou.mvp.shopping.center.model.bean.ProductImageList@1033f68, productPrice='259.72', originPrice='755.00', place='浙江 杭州', sellCount='1159', sellerType='1', sellerName='eoodoo旗舰店', sellerId=2832303009, uiType=0, testData='null')

创建新对象的结果,* 这看起来不错:*

  1. Product(productId=0, productName='', productUrl='', productPic='', productPics=com.laka.ergou.mvp.shopping.center.model.bean.ProductImageList@1c228b, productPrice='', originPrice='', place='', sellCount='', sellerType='', sellerName='', sellerId=0, uiType=1, testData='testData')

这里是我使用的JSON。但是像uiType和testData这样的字段。只是我在代码中定义的字段,并在本地使用,这些不是服务器恢复json字段

  1. {
  2. "tbk_item_get_response":{
  3. "results":{
  4. "n_tbk_item":[
  5. {
  6. "item_url":"http://item.taobao.com/item.htm?id=582889134126",
  7. "nick":"宝绒羊服饰旗舰店",
  8. "num_iid":582889134126,
  9. "pict_url":"https://img.alicdn.com/tfscom/i1/1720028843/O1CN01ERqlHz2FC8tL1m2tz_!!0-item_pic.jpg",
  10. "provcity":"浙江 杭州",
  11. "reserve_price":"1318.00",
  12. "seller_id":1720028843,
  13. "small_images":{
  14. "string":[
  15. "https://img.alicdn.com/tfscom/i4/1720028843/O1CN01xD9JyD2FC8tJMRuk2_!!1720028843.jpg",
  16. "https://img.alicdn.com/tfscom/i4/1720028843/O1CN01twbf3O2FC8tLEHVJc_!!1720028843.jpg",
  17. "https://img.alicdn.com/tfscom/i4/1720028843/O1CN01zM2clN2FC8tE0LO5q_!!1720028843.jpg",
  18. "https://img.alicdn.com/tfscom/i3/1720028843/O1CN01WW6xzz2FC8tKjoitz_!!1720028843.jpg"
  19. ]
  20. },
  21. "title":"羽绒服女2018新款女装冬季短款韩版时尚银色亮面滩羊毛领加厚外套",
  22. "user_type":1,
  23. "volume":2138,
  24. "zk_final_price":"498.00"
  25. }
  26. ]
  27. },
  28. "total_results":19643,
  29. "request_id":"kvbqd1jrgqcg"
  30. }

}

vktxenjb

vktxenjb1#

你应该为所有的字段设置默认值,如果所有的字段都有默认值,那么当JSON中缺少相应的字段时,Gson会尊重这些默认值。

yhxst69z

yhxst69z2#

Gson目前正在破坏Kotlin类型安全。它可以将null写入非null属性。当您阅读的json将该字段赋值为null时,可能会发生这种情况。例如,如果您有数据类:

  1. data class A (
  2. var nonNullable: String = "",
  3. var other: Int = 42
  4. )

下面是JSON:

  1. {
  2. "nonNullable": null,
  3. "other": 91
  4. }

结果是nonNullable中包含null
为了避免这种情况,您可以为类创建自定义GSON类型转换器,或者使nonNullable实际上可为空,但提供getter和setter,这将忽略null值:

  1. class A {
  2. var nonNullable: String? = ""
  3. get() = field ?: ""
  4. set(value) {
  5. if (value != null) {
  6. field = value
  7. }
  8. }
  9. }

0也是一样--这意味着您解析JSON将该字段赋值为零或者,如果不是这样--请提供您JSON以使问题更清楚

展开查看全部
uqzxnwby

uqzxnwby3#

还有另一种方法可以使参数保持非空。

  1. data class User(val username: String = "User")

您需要做的就是定义自定义InstanceCreator

  1. class UserInstanceCreator : InstanceCreator<User> {
  2. override fun createInstance(type: Type?): User {
  3. return User()
  4. }
  5. }

并在创建GsonBuilder

  1. GsonBuilder()
  2. .registerTypeAdapter(User::class.java, UserInstanceCreator())
  3. .create()

由于这样,您的对象将使用默认值创建,因此您可以保持属性非空。

展开查看全部

相关问题