Menu

Avoiding printing null values

Help
2008-03-26
2020-08-12
  • Jerome Banks

    Jerome Banks - 2008-03-26

      Hey,
       We're writing an application which serializes JSON , and we want to minimize output as much as possible for efficiency reasons.  In particular, we would like to turn off the serialization of a property if the value is null, since this simply adds more output, and doesn't necessarily send any more information.  Also, if we have an array, we want to serialize if the array is non-empty, but if it is empty, we don't want to send it.

    E.g

    if we have
      class A {
         public String getMyField();
         public ArrayList<String> getMyArray();
      }
    if getMyField() returns "aValue" , and getMyArray() contains "first value", "second value"; then we want to return
    {
      "myField":"aValue",
      "myArray":["first value","second value"]
    }
    if getMyField() returns null , and getMyArray() has no elements, we just want
    { }
    instead of
    { "myField":null,
       "myArray":[]
    }

      Is this possible with a special Transformer, or with the exclude() method somehow?
      Removing the nulls would substantially cut down our data transmission, and our client processing ....

      Thank you for sharing flexjson .....
    thx .....
    - --jerome

     
    • Charlie Hubbard

      Charlie Hubbard - 2008-03-27

      Yea.  I've given it a lot of thought, and I don't think there's a way to handle this without changing the guts of flexjson.  Although it might be a nice feature to have.  I'm thinking something like:

      new JSONSerializer().includeNulls(false).serialize( myObject );

      Charlie

       
    • Mike Viens

      Mike Viens - 2008-08-28

      I strongly encourage adding the .includeNulls() option!  I came to this forum to find the answer to this exact question.  And to support the second request from Jerome, you could add a .includeEmpty() option, too.

      Mike V.

       
    • Charlie Hubbard

      Charlie Hubbard - 2008-09-18

      I want to be careful how many of these little config options we add since it can get overwhelming about what it does.  I think with the changes made to Transformers we could accomplish the same sort of thing without needing to add a method every time we want a different outcome.

      Charlie

       
  • bill sembiante

    bill sembiante - 2020-08-12

    Logged in to check the same thing. We are serializing objects that can contain many nulls, and the size of the file is quite large. It would be very helpfull to remove the nulls as an option. Otherwise, at this point, we have no choice but use a Jackson custom serializer and check each field (e.g. if (foo != null) { jgen.writeStringField("foo", i.getfoo()). Not an ideal solution when our objects have dozens of private variables.

     

Log in to post a comment.

MongoDB Logo MongoDB