I want to remove attributes that have empty collections or null values using gson.
Aiperiodo periodo = periodoService();
//periodo comes fro
I tried a solution of @Braj in Kotlin. The idea is to convert JSON to Map, remove nulls and empty arrays, then convert Map back to JSON string.
But it has several disadvantages.
Object is not recognized as int).Alternatively you can try to use Moshi instead of Gson, see Broken server response handling with Moshi.
After couple of days I overcame a 1st problem for complex JSONs.
import android.support.annotation.NonNull;
import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
public class GsonConverter {
private Type type;
private Gson gson;
public GsonConverter() {
type = new TypeToken
Usage:
YourJsonObject yourJsonObject = new Gson().fromJson(new GsonConverter().cleanJson(json), YourJsonObject.class);
For those who want to use @Braj solution, here is a code in Kotlin.
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import java.lang.reflect.Type
class GsonConverter {
private val type: Type = object : TypeToken>() {}.type
private val gson = Gson()
private val gsonBuilder: GsonBuilder = GsonBuilder()//.setLongSerializationPolicy(LongSerializationPolicy.STRING)
fun convert(jsonString: String): String {
val data: Map = gson.fromJson(jsonString, type)
val obj = data.filter { it.value != null && ((it.value as? ArrayList<*>)?.size != 0) }
val json = gsonBuilder/*.setPrettyPrinting()*/.create().toJson(obj)
println(json)
return json
}
}