Json数据异常兼容处理

跟后端定义联调接口,总会碰到一些异常的情况,比如本来应该返回一个数组的,由于数据库没查到东西后台就给返回了一个空字符串,由于我们前端是用数组来接受数据的,返回了一个字符串,前端就会出错闪退,此时要么跟后端撕逼,还有种方法就是我们自己兼容,我就说说后面的方法。

import com.google.gson.Gson
import com.google.gson.GsonBuilder
import java.lang.reflect.Type
import java.text.DateFormat

/**

  • json转换工具类
    */
    object JsonUtil {
    private val LOG_TAG = JsonUtil::class.java.name
    val gson: Gson = getFormatGson()

    fun unpack(jsonString: String, clazz: Class): T? {
    return try {
    gson.fromJson(jsonString, clazz)
    } catch (e: Exception) {
    LogUtil.e(LOG_TAG, e.localizedMessage)
    null
    }
    }

    fun unpack(jsonString: String, type: Type): T? {
    return try {
    gson.fromJson(jsonString, type)
    } catch (e: Exception) {
    LogUtil.e(LOG_TAG, e.localizedMessage)
    null
    }
    }

    fun pack(o: Any?): String {
    if (o == null) {
    return “”
    }
    return try {
    gson.toJson(o)
    } catch (e: Exception) {
    LogUtil.e(LOG_TAG, e.localizedMessage)
    “”
    }
    }

    fun pack(o: Any?, type: Type): String {
    if (o == null) {
    return “”
    }
    return try {
    gson.toJson(o, type)
    } catch (e: Exception) {
    LogUtil.e(LOG_TAG, e.localizedMessage)
    “”
    }
    }

    private fun getFormatGson(): Gson {
    val builder = GsonBuilder()
    builder.registerTypeAdapter(java.util.Date::class.java, DateDeserializer()).setDateFormat(DateFormat.LONG)
    builder.registerTypeAdapter(java.util.Date::class.java, DateSerializer())
    .setDateFormat(DateFormat.LONG)
    builder.registerTypeAdapter(Long::class.java, LongDefault0Adapter())
    builder.registerTypeAdapter(java.lang.Long::class.java, LongDefault0Adapter())
    builder.registerTypeAdapter(Int::class.java, IntegerDefault0Adapter())
    builder.registerTypeAdapter(Integer::class.java, IntegerDefault0Adapter())
    builder.registerTypeAdapter(Double::class.java, DoubleDefault0Adapter())
    builder.registerTypeAdapter(java.lang.Double::class.java, DoubleDefault0Adapter())
    builder.registerTypeAdapter(Float::class.java, FloatDefault0Adapter())
    builder.registerTypeAdapter(java.lang.Float::class.java, FloatDefault0Adapter())
    builder.registerTypeAdapter(String::class.java, StringDefault0Adapter())
    builder.registerTypeAdapter(java.lang.String::class.java, StringDefault0Adapter())
    return builder.create()
    }
    }

数组兼容处理


import com.baoer.toolkit.LogUtil
import com.google.gson.Gson
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import java.lang.reflect.Type
import java.util.*

/**
 * Json数组解析处理 兼容异常
 */
class ArraySecurityAdapter : JsonDeserializer<List<*>> {
    override fun deserialize(
        json: JsonElement?,
        typeOfT: Type?,
        context: JsonDeserializationContext?
    ): List<*> {
        if (json == null ||!json?.isJsonArray!!) {
            LogUtil.e("error --- requrie array but get none array---${json.toString()}")
            return Collections.EMPTY_LIST
        }
        return try {
            val newGson = Gson()
            return newGson.fromJson(json, typeOfT)
        } catch (e: NumberFormatException) {
            LogUtil.e("error --- 解析数组出错")
            Collections.EMPTY_LIST
        }
    }
}

还有的情况,本来应该返回一个数字,结果返回了一个字符串或者空串,兼容代码:

import com.google.gson.*
import java.lang.reflect.Type

/**
 * Integer解析
 */
class IntegerDefault0Adapter : JsonSerializer<Int?>, JsonDeserializer<Int> {
    @Throws(JsonParseException::class)
    override fun deserialize(
        json: JsonElement,
        typeOfT: Type,
        context: JsonDeserializationContext
    ): Int {
        try {
            if ("" == json.asString || "null" == json.asString) { //定义为int类型,如果后台返回""或者null,则返回0
                return 0
            }
        } catch (ignore: Exception) {
        }
        return try {
            json.asInt
        } catch (e: NumberFormatException) {
            0
        }
    }

    override fun serialize(
        src: Int?,
        typeOfSrc: Type,
        context: JsonSerializationContext
    ): JsonElement {
        return JsonPrimitive(src)
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值