Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why static fields not serialized using google.gson.GsonBuilder JSON parser?

Tags:

I tried serializing an object using google.gson.GsonBuilder as follows:

public class JsonHelper
{
    public static String ToJson(Object o, Type oType)
    {
        Gson gson = new().setPrettyPrinting().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
        gson.toJson(o, oType);
    }
}

public class JsonTest
{
   public static String staticField;

   public static String ToJson()
   {
       JsonTest newJsonTest = new JsonTest();
       newJsonTest.staticField = TelephoneStatus.GetPhoneIMEI(); // let's say we use static field to keep IMEI

       Type oType = new TypeToken<JsonTest>(){}.getType();
       return JsonHelper.ToJson(newJsonTest, oType);
   }
}

Return value for JsonTest class method ToJson() is empty. If i change staticField field declaration to be non-static, it works as expected. Considering why static fields are not serialized, should it be considered as a bug? Or is it considered unnecessary?

If i had a list of JsonTest i wouldn't expect having static field parsed and written multiple times but once. However, isn't it better than missing it at all?