Uploaded image for project: 'Spring Framework'
  1. Spring Framework
  2. SPR-16461

GSON converter only serialises fields of controller method return type, ignoring subclass fields of response object

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Closed
    • Priority: Major
    • Resolution: Complete
    • Affects Version/s: 4.3.14, 5.0.3
    • Fix Version/s: 4.3.15, 5.0.4
    • Component/s: Web
    • Labels:

      Description

      The GSON message converter used to serialise using the class of the object that was being serialised. Now it uses the return type of the controller method.

      So when I have

      @GetMapping("/animal")
      public Animal getAnimal() { return new Cat(...); }
      

      the Cat-specific fields do not get serialised, only Animal fields.

      Workarounds:

      • When I replace GSON with Jackson on the classpath, Cat fields get serialised again.
      • When I subclass the GsonHttpMessageSerializer and override writeInternal as follows:
      @Override
      protected void writeInternal(Object o, @Nullable Type type, Writer writer) throws Exception
      {
          // replaces the type info with null value
          super.writeInternal(o, null, writer); 
      }
      

      the Cat fields get serialized again.

      Probably introduced in SPR-12811, the last version that serialized Cats as Cats was 4.1.9.

      To reproduce:
      Run the repro project, and GET http://localhost:8080/SPR-16461/animal
      Response should be the same as http://localhost:8080/SPR-16461/cat but isn't.

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              juergen.hoeller Juergen Hoeller
              Reporter:
              fdlk Fleur Kelpin
              Last updater:
              Spring Issues Spring Issues
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

                Dates

                Created:
                Updated:
                Resolved:
                Days since last comment:
                3 years, 25 weeks, 2 days ago