Yo uso GSON para convertir la clase de datos que la remontada del servidor. y definir la clase de datos como este ... Y no hay algún campo no quiero convertir con GSON .. Así que añadir la ExclusionStrategy con anotación. A través de la prueba, he encontrado que AnnotationExclusionStrategy operando normalmente, y omitir el campo no quiero convertir. Añado anotación con el campo como uiType y TestData, pero en realidad al imprimir el objeto. Me pareció que el uiType campo y TestData tenido convertido a cero y nula ..
Luego de crear una nueva clase de datos. la uiType y TestData no habían borrado a cero o null.Is ir mal cuando GSON convertir ??
si hay alguna manera de resolver este problema?
Aquí está el código.
entidad clase de datos:
data class Product(@SerializedName("num_iid") var productId: Long,
@SerializedName("title") var productName: String,
@SerializedName("item_url") var productUrl: String,
@SerializedName("pict_url") var productPic: String,
@SerializedName("small_images") var productPics: ProductImageList,
@SerializedName("zk_final_price") var productPrice: String,
@SerializedName("reserve_price") var originPrice: String,
@SerializedName("provcity") var place: String,
@SerializedName("volume") var sellCount: String,
@SerializedName("user_type") var sellerType: String,
@SerializedName("nick") var sellerName: String,
@SerializedName("seller_id") var sellerId: Long
) : MultiItemEntity {
@Exclude
@ShoppingCenterConstant.ProductListUiType
var uiType = ShoppingCenterConstant.LIST_UI_TYPE_COMMON
var testData = "TestData"
override fun getItemType(): Int {
return ShoppingCenterConstant.LIST_UI_TYPE_COMMON
}
override fun toString(): String {
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')"
}
}
GSON AnnotationExclusion:
public class AnnotationExclusion implements ExclusionStrategy {
public static final String TAG = GsonUtil.TAG;
@Override
public boolean shouldSkipField(FieldAttributes f) {
boolean isShouldSkip = f.getAnnotation(Exclude.class) != null;
return isShouldSkip;
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
boolean isShouldSkip = clazz.getAnnotation(Exclude.class) != null;
return isShouldSkip;
}
}
El lugar en el que Impresión:
override fun showData(data: BaseListBean<Product>) {
var product = Product(0, "", "", ""
, ProductImageList(List(0, { String() })), "", "", "", ""
, "", "", 0)
LogUtils.info("print out new product:" + product)
mResultListener.onResponse(data)
}
Resultado con GSON convertidor , y se puede ver el campo y uiType TestData tenían convertir a cero o nulo:
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')
Resultado con crear un nuevo objeto , esto parece muy bien:
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')
Aquí está el JSON que solía .Pero el campo como uiType y TestData. sólo el campo i defino en el código y usados en locales, estos no son el campo JSON reaparición del servidor
{
"tbk_item_get_response":{
"results":{
"n_tbk_item":[
{
"item_url":"http://item.taobao.com/item.htm?id=582889134126",
"nick":"宝绒羊服饰旗舰店",
"num_iid":582889134126,
"pict_url":"https://img.alicdn.com/tfscom/i1/1720028843/O1CN01ERqlHz2FC8tL1m2tz_!!0-item_pic.jpg",
"provcity":"浙江 杭州",
"reserve_price":"1318.00",
"seller_id":1720028843,
"small_images":{
"string":[
"https://img.alicdn.com/tfscom/i4/1720028843/O1CN01xD9JyD2FC8tJMRuk2_!!1720028843.jpg",
"https://img.alicdn.com/tfscom/i4/1720028843/O1CN01twbf3O2FC8tLEHVJc_!!1720028843.jpg",
"https://img.alicdn.com/tfscom/i4/1720028843/O1CN01zM2clN2FC8tE0LO5q_!!1720028843.jpg",
"https://img.alicdn.com/tfscom/i3/1720028843/O1CN01WW6xzz2FC8tKjoitz_!!1720028843.jpg"
]
},
"title":"羽绒服女2018新款女装冬季短款韩版时尚银色亮面滩羊毛领加厚外套",
"user_type":1,
"volume":2138,
"zk_final_price":"498.00"
}
]
},
"total_results":19643,
"request_id":"kvbqd1jrgqcg"
}
}
Actualmente se está rompiendo Gson Kotlin seguridad de tipos. Se puede escribir nulo a la propiedad no nulo. Eso puede suceder cuando JSON que la lectura tiene ese campo asignado a nulo. Por ejemplo, si usted tiene la clase de datos:
data class A (
var nonNullable: String = "",
var other: Int = 42
)
Y siguiendo JSON:
{
"nonNullable": null,
"other": 91
}
Tendrá null
en nonNullable
como resultado.
Para evitar que se pueden crear convertidor de tipos GSON personalizado para su clase o hacer nonNullable
realidad anulable, pero proporcionan get y set, que pasará por alto null
valor:
class A {
var nonNullable: String? = ""
get() = field ?: ""
set(value) {
if (value != null) {
field = value
}
}
}
Y lo mismo con 0 - Eso significa que JSON que el análisis sintáctico tienen ese campo asignado a cero. O, si no es así - nos proporciona su JSON para hacer más clara la pregunta.