DonaldDu / google-gson

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

Support custom String stub for null values #416

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?

import java.util.HashMap;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GsonNullExample {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("key", null);
        Gson gson = new GsonBuilder().serializeNulls().create();
        System.out.println(gson.toJson(map));
    }
}

What is the expected output? What do you see instead?
The output is:
   {"key":null}

I would like the option to set a custom value for null, e.g. "" :
   {"key":""}

Perhaps serializeNulls() could be overloaded to serializeNulls(String 
nullStringValue), to allow custom String instead of the word "null".

What version of the product are you using? On what operating system?
gson 2.1 on Mac OSx using Eclipse.

Please provide any additional information below.

Original issue reported on code.google.com by a...@matan.name on 28 Feb 2012 at 5:48

GoogleCodeExporter commented 9 years ago
Low priority. I'm not a fan of the requested behavior.

Original comment by limpbizkit on 18 Mar 2012 at 5:23

GoogleCodeExporter commented 9 years ago
Then there's another way to deserialize fields with null value? I'm triying to 
deserialize a field expecting a string but if it's null it crashes.

Original comment by nagash...@gmail.com on 20 Mar 2012 at 1:29

GoogleCodeExporter commented 9 years ago
We fixed it by allowing you to register a custom type adapter for strings. In 
this case your type adapter would read in the empty string and write out null, 
and vice versa.

Original comment by limpbizkit on 1 Jul 2012 at 5:58

GoogleCodeExporter commented 9 years ago
I am using gson-2.2.2.jar. is it solved in release 2.2.2? I added string custom 
type adapter. It just calls serialize method for non NULL strings. I also build 
Gson object using serializeNulls() call. It does not call serialize for NULL 
string object fields.

Original comment by vinod.el...@gmail.com on 29 Oct 2012 at 9:31