Cron9000 / google-gson

Automatically exported from code.google.com/p/google-gson
0 stars 0 forks source link

Exclude empty array in Gson serialization #512

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?
1. In Java class, define an attribute as List
    private List<Score> Scores = new ArrayList<Score>();
2. If Score (ArrayList) is not populated or empty, while generating JSON file, 
an empty array is getting generated

        ],
        "scores": []
      },

What is the expected output? What do you see instead?

Option 1 - If a collection or an array is empty, it should not generate an 
empty array.

Example - com.google.gson.internal.bind.CollectionTypeAdapterFactory.write()
existing code -  if (collection == null) {
expected -      if (collection == null || collection.size() < 1) {

Option 2 - configuration property to enable/disable adding empty array, similar 
to Jackon SerializationFeature.WRITE_EMPTY_JSON_ARRAYS 
(http://wiki.fasterxml.com/JacksonFeaturesSerialization)

What version of the product are you using? On what operating system?
version 2.2.3
operating system - Mac OSX 10.8.3

Please provide any additional information below.

Original issue reported on code.google.com by chanda...@gmail.com on 1 May 2013 at 5:25

GoogleCodeExporter commented 9 years ago
This is very annoying to me.
We designed a format with many optional fields (lists in different types), and 
it shows all these empty optional fields.

Original comment by Charles....@gmail.com on 1 Jul 2013 at 2:26

GoogleCodeExporter commented 9 years ago
Possible solution?

  public String toJson(Object src, Type typeOfSrc) {
    StringWriter writer = new StringWriter();
    toJson(src, typeOfSrc, writer);

    String jsonObject = writer.toString();

    if (src instanceof ArrayList) {
        if(jsonObject.contains("[")){               
            int index = jsonObject.indexOf("[");
            char nextChar = jsonObject.charAt(index + 1);

            if(nextChar == ']'){
                jsonObject = null;              
            }
        }       
    }

    return jsonObject;

  }

Original comment by Ewerto...@gmail.com on 20 Aug 2013 at 1:44

GoogleCodeExporter commented 9 years ago
I have a tangentially related issue. I feel that it is unnecessary to start a 
new case so I'll write it here.

Sometimes I receive a -1 or 0 for when the Json array contains nothing. For 
example, usually there might be a field "api_array":[1,2,3], but when the array 
has nothing I get "api_array":-1 instead.

Currently I'm using a workaround as suggested by the folks on StackOverflow, 
but I feel that there should be some elegant way of telling Gson that "If the 
expected array has only 1 field or nothing, skip it or otherwise mark it as 
blank".

Perhaps a flag in GsonBuilder?

Original comment by undisputed.seraphim on 16 Dec 2013 at 10:08