本文介绍了为什么不使用google.gson.GsonBuilder JSON解析器对静态字段进行序列化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 google.gson.GsonBuilder 对对象进行序列化,如下所示:

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);
   }
}

类方法ToJson()的

返回值为空.如果我将staticField字段声明更改为非静态,它将按预期工作.考虑为什么不对静态字段进行序列化,应该将其视为 bug 吗?还是认为它是不必要的?

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?

如果我的 list 为JsonTest,我不会期望静态字段被多次解析和写入 一次,而一次.但是,难道不是比完全错过它更好吗?

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?

推荐答案

Java序列化仅序列化对象的非静态和非瞬态字段,因为,

Java Serialization only serialize object's non-static and non-transient fields because,

参考

在静态字段状态的情况下,它不仅属于任何特定对象,还将属于所有类.

In case of static field state not only belongs to any specific object it will belongs to all class.

因此,静态字段将处于任何特定对象的状态下.

So the static field would be comes under state of any specific object.

这篇关于为什么不使用google.gson.GsonBuilder JSON解析器对静态字段进行序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 18:43