Search code examples
javajsongsonjson-deserialization

Gson custom deserializer for String class


I am using GSON to convert a json to a POJO but values of the keys in json may contain whitespaces and I wanted to trim them. For that I wrote a custom String deserializer but that isn't working. Here is want I have:

public class Foo {
  public int intValue;
  public String stringValue;

  @Override
  public String toString() {
      return "**" + stringValue + "**" ;
  }
}

public void testgson()
{
    String json = "{\"intValue\":1,\"stringValue\":\" one two  \"}";
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(String.class, new StringDeserializer());
    Gson gson = gsonBuilder.create();
    Foo a = gson.fromJson(json, Foo.class);
    System.out.println(a.toString()); //prints ** one two ** instead of **one two**

}

class StringDeserializer implements JsonDeserializer<String>
{
    @Override public String deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException
    {
        String a = json.toString().trim();
        System.out.print(a); //prints ** one two **
        return a;
    }
}

I expected the output to be **one two** but that isn't the case. What am I doing wrong


Solution

  • In your StringDeserializer, this

    json.toString()
    

    is calling toString on a JsonElement that is specifically a JsonPrimitive containing a value that is text. Its toString implementation returns the JSON representation of its content, which is, literally, the String " one two ". trim doesn't do what you want it because that String is enclosed in ".

    What you really wanted to do was read the content of the JSON element. You can do that with one of JsonElement's convenience method: getAsString().

    So

    String a = json.getAsString().trim();
    

    would then print what you expected.