Gson v2.0 Release Notes

  • 2011-11-13

    Faster

    • Previous versions first parsed complete document into a DOM-style model (JsonObject or JsonArray) and then bound data against that. Gson 2 does data binding directly from the stream parser.

    More Predictable

    • Objects are serialized and deserialized in the same way, regardless of where they occur in the object graph.

    🔄 Changes to watch out for

    • Gson 1.7 would serialize top-level nulls as "". 2.0 serializes them as "null".

      String json = gson.toJson(null, Foo.class);
      1.7: json == ""
      2.0: json == "null"
      
    • Gson 1.7 permitted duplicate map keys. 2.0 forbids them.

      String json = "{'a':1,'a':2}";
      Map<String, Integer> map = gson.fromJson(json, mapType);
      1.7: map == {a=2}
      2.0: JsonSyntaxException thrown
      
    • Gson 1.7 won’t serialize subclass fields in collection elements. 2.0 adds this extra information.

      List<Point2d> points = new ArrayList<Point2d>();
      points.add(new Point3d(1, 2, 3));
      String json = gson.toJson(points,
          new TypeToken<List<Point2d>>() {}.getType());
      1.7: json == "[{'x':1,'y':2}]"
      2.0: json == "[{'x':1,'y':2,'z':3}]"
      
    • Gson 1.7 binds single-element arrays as their contents. 2.0 doesn’t.

      Integer i = gson.fromJson("[42]", Integer.class);
      1.7: i == 42
      2.0: JsonSyntaxException thrown
      

    Other changes to be aware of

    • Gson 2.0 doesn’t support type adapters for primitive types.
    • Gson 1.7 uses arbitrary precision for primitive type conversion (so -122.08e-2132 != 0). Gson 2.0 uses double precision (so -122.08e-2132 == 0).
    • Gson 1.7 sets subclass fields when an InstanceCreator returns a subclass when the value is a field of another object. Gson 2.0 sets fields of the requested type only.
    • Gson 1.7 versioning never skips the top-level object. Gson 2.0 versioning applies to all objects.
    • Gson 1.7 truncates oversized large integers. Gson 2.0 fails on them.
    • Gson 2.0 permits integers to have .0 fractions like "1.0".
    • Gson 1.7 throws IllegalStateException on circular references. Gson 2.0 lets the runtime throw a StackOverflowError.