Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gson: Treat null as empty String

Tags:

json

parsing

gson

I use google-gson to serialize a Java map into a JSON string. It provides a builder handles null values:

Gson gson = new GsonBuilder().serializeNulls().create(); 

The problem is that the result is the string null, as in:

gson.toJson(categoriesMap)); {"111111111":null} 

And the required result is:

{"111111111":""} 

I can do a String-replace for null and "", but this is ugly and prone to errors. Is there a native gson support for adding a custom String instead of null?

like image 589
Adam Matan Avatar asked Feb 28 '12 14:02

Adam Matan


1 Answers

The above answer works okay for serialisation, but on deserialisation, if there is a field with null value, Gson will skip it and won't enter the deserialize method of the type adapter, therefore you need to register a TypeAdapterFactory and return type adapter in it.

Gson gson = GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create();   public static class NullStringToEmptyAdapterFactory<T> implements TypeAdapterFactory {     public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {          Class<T> rawType = (Class<T>) type.getRawType();         if (rawType != String.class) {             return null;         }         return (TypeAdapter<T>) new StringAdapter();     } }  public static class StringAdapter extends TypeAdapter<String> {     public String read(JsonReader reader) throws IOException {         if (reader.peek() == JsonToken.NULL) {             reader.nextNull();             return "";         }         return reader.nextString();     }     public void write(JsonWriter writer, String value) throws IOException {         if (value == null) {             writer.nullValue();             return;         }         writer.value(value);     } } 
like image 132
oznus Avatar answered Sep 26 '22 11:09

oznus