dev90
dev90

Reputation: 7549

GSON raises exception if object type is different

I am using following approach to parse feed into Java Objects.

   val gsonBuilder = GsonBuilder()
        val gson = gsonBuilder.create()
        var homeModel: DataModel?=null

        try {
            homeModel = gson.fromJson(response, DataModel::class.java)
        }catch (ex:java.lang.Exception){
        }

This works fine if feed comes in the same format, but it type of some object changes it lands into exception block.

For example, feed some time provides "integers" instead of Object in "data"

@SerializedName("data")
@Expose
private List<MoreData> data = null;

I want to know if there is any possibility in GSON to set specific data to "null" if type does not match.

Upvotes: 2

Views: 238

Answers (1)

ycannot
ycannot

Reputation: 1947

you need to change your data type of "data" with List<Object> for java or List<Any> for kotlin. probably you will get rid of exception.

@SerializedName("data")
@Expose
private List<Object> data = null;

but you will need to cast items to appropriate types while you are using.

For example:

val item:Int = homeModel[i] as Int //as yourDesiredType

However, if you want to set "data" null when data type is different, you can try:

val model = DataModel()
val json = Gson().toJson(model)
homeModel = Gson().fromJson(json, DataModel::class.java)
try {
        if(!homeModel.data.isNullOrEmpty()){
            homeModel.data.first() as String //as yourDesiredType
        }
} 
catch (ex:java.lang.Exception){
    homeModel.data = null
}

Upvotes: 1

Related Questions