Question

I have been using gson to serialize objects and send json data to the front-end. It always worked as expected in the past.

Now I have an class. It has an object field called "destination". The owning class is serialized correctly, but the the object field does not get serialized, and further, its json data has a mysterious field named "handler" (the class for "destination" does not have this "handler" field).

Here is the json data (it shows the idea):

{
    name: my name (this gets serialized)

    destination: {
        seq: 0   (this does not get serizlied. 0 is the default)
        validation: true (this does not get serialized. true is the default)

        (don't konw why this handler is here)
        handler: {
            Object { interfaces=[1], constructed=true, persistentClass={...}, more...}
            constructed: true
            entityName:"abc.MyClass"
            initialized: true
            interfaces: [Object {}]
            overridesEquals: false
            persistentClass: Object {}
            readOnly: false
            specjLazyLoad: false
            target: Object { validation=false, seq=2,  more...}   (this object contains all the actual values)
            unwrap: false   
        }
    }   
}

Interestingly, the "handler" has a property called "target", which has all the serialized data.

Here is my Java code:

    Gson gson = new GsonBuilder().create();
    String  json = gson.toJson(myData); 

Does anyone ever see this "handler" situation? What I do could be wrong?

I use gson 1.7.1.

Thanks!

Was it helpful?

Solution

Gson uses only fields private,public,protected via Java Reflection API

(don't konw why this handler is here)
    handler: { ....}

Gson is not doing magic, during serialization to add extra handler filed object in JSON, if it is coming in generated json means you've handler property some where inside destination class, check your code again. If you find it then you can ignore using Expose annotation

@Expose(serialize = false) // don't serialize handler field during serialization process private Handler handler;

Interestingly, the "handler" has a property called "target", which has all the serialized data.

nothing interestingly, means you have handler property inside your destination object, that why you seeing it in generated json.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top