GsonFactory null deserialization

796 views
Skip to first unread message

Savchenko Dmitry

unread,
Oct 27, 2011, 5:41:34 AM10/27/11
to google-http-java-client
I'm using google-http-java-client and GsonFactory as json factory.
WHen I get JSON object like this

{"to_latlnt" : null, "phone" : 77777777777}
GSON deserialize to_latlng as not-null object (I can call his setter
and getters), but it must be null. How can I make it to do this?

Yaniv Inbar (יניב ענבר)

unread,
Oct 31, 2011, 4:15:13 PM10/31/11
to google-http...@googlegroups.com
This is actually by design.  We want to be able to differentiate between Java null -- meaning there is no value -- and the literal value JSON null.  To check if something is JSON null, use Data.isNull(Object).  To make this more concrete, please run this example:

  private static final String JSON = "{\"to_latlnt\" : null, \"phone\" : 77777777777}";

  public static class Parsed {
    @Key public String to_latlnt;
    @Key public Long phone;
    @Key public String unspecified;
  }
  
  public static void main(String[] args) throws IOException {
    JsonFactory factory = new GsonFactory();
    Parsed parsed = factory.fromString(JSON, Parsed.class);
    System.out.println("parsed JSON: " + factory.toString(parsed));
    System.out.println("to_latlnt: " + show(parsed.to_latlnt));
    System.out.println("phone: " + show(parsed.phone));
    System.out.println("unspecified: " + show(parsed.unspecified));
  }
  
  public static String show(Object value) {
    if (value == null) {
      return null;
    }
    return Data.isNull(value) ? "JSON null" : value.toString();
  }

Yaniv Inbar
Senior Software Engineer
Google Inc.
Reply all
Reply to author
Forward
0 new messages