Question

In manual there is a sample, containing only primitive case.

What if my case is not primitive?

Suppose I have a class, which has a problems with default serializing (in my case it is endless recursion).

Th class contain multiple fields, some of them are "main" and hold the information while another ones are service.

So I need to serialize only "main" fields and derive service ones from them.

class MyType1 {
   MyType2 a; // "main" field
   MyType3 b; // service fiels
}

class MySerializer implements JsonSerializer<MyType1> {
    @Override
    public JsonElement serialize(MyType1 arg0, Type arg1, JsonSerializationContext arg2) {
        JsonObject ans = new JsonObject();
        // ans.add("a", ... // what to write here? How to wrap a into JsonElement?
        return ans;
    }
}

I know I can use transient keyword for this specific case. But the question is about writing serializers.

UPDATE

I emphasize that using transient is not an answer. My question is about custom serializers. How to write them?

No correct solution

OTHER TIPS

class MyTypeToSerialize {
   MyType2 a; // "main" field
}

class MyType1 extends MyTypeToSerialize {
   MyType3 b; // service fiels
}

If you just want the field MyType2 a to be serialized/deserialized then use MyTypeToSerialize (you don't need a custom serializer or deserialiser)

Edit: @Brian Roach's suggestion is better and easier solution:

class MyType1 {
   MyType2 a; // "main" field
   transient MyType3 b; // service fiels
}

Edit2:

So I need to serialize only "main" fields and derive service ones from them.

So use on of the suggestions above.

I know I can use transient keyword for this specific case. But the question is about writing serializers.

Why do you think you need serializers?

One should use context.serialize to delegate, like this:

class MySerializer implements JsonSerializer<MyType1> {
    @Override
    public JsonElement serialize(MyType1 arg0, Type arg1, JsonSerializationContext arg2) {
        JsonObject ans = new JsonObject();
        JsonElement a = arg2.serialize(a);
        ans.add("a", a);
        return ans;
    }
}

I found an answer here: http://www.javacreed.com/gson-serialiser-example/ , section "Nested Objects"

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