emfjson / emfjson-jackson

JSON Binding for Eclipse Modeling Framework
https://emfjson.github.io
Other
80 stars 23 forks source link

Question: Is there a way to achieve selective serialization? #80

Closed tarelli closed 8 years ago

tarelli commented 8 years ago

Is there any way to serialize only certain objects within a model (without having to duplicate those objects in another root for the sole purpose of serializing them)? Thanks!

ghillairet commented 8 years ago

Not really anything like that, how would you filter those objects? If you want to filter by type, and you have generated the code from your ecore model, you can try to register a JsonSerializer for the types you don't want to the module, and leave the implementation of the serailize method empty. But I'm not sure it would work.

tarelli commented 8 years ago

What if all objects were to implement an interface with an attribute "serialise" which could be true or false, what would be the way to check suck attribute to skip an object altogether during serialisation if serialise==false?

tarelli commented 8 years ago

@ghillairet We could have a custom version of the EObjectSerializer is there any way to use one without forking the project? Thanks!

ghillairet commented 8 years ago

You can try something like that, register empty serializers for the type you don't want.

ObjectMapper mapper = new ObjectMapper();
ResourceSet resourceSet = new ResourceSetImpl();
EMFModule module = new EMFModule(resourceSet);
module.addSerializer(MyClass.class, new JsonSerializer<MyClass>() {
    @Override
    public void serialize(MyClass value, JsonGenerator gen, SerializerProvider serializers) 
       throws IOException {
    }
});
mapper.registerModule(module);

mapper.writeValueAsString(myResource);
ghillairet commented 8 years ago

In the next version, I will start to introduce annotations similar to annotations in Jackson, like @JsonIgnore, that could be used to support that use case.

tarelli commented 8 years ago

@ghillairet it's not going to be based on the class but rather on the value of an attribute so I'd need some place where I have the object and depending on the value of a field do different things (serialize vs don't serialize) that's why I was thinking about a custom version of the EObjectSerializer

ghillairet commented 8 years ago

You can still register your own serializers for the types for which you want to support that, the same way. Or you can have your own EObjectSerializer that extends the default one, and register it like that, it will override the default one.

module.addSerializer(EObject.class, new MyEObjectSerializer());
tarelli commented 8 years ago

@ghillairet thanks, seems to work!