How to serialize an EObject from Xtext

The Xtext framework is pretty awesome. It includes a lot of built-in features: syntax highlight, custom editors, etc. This is the framework we are currently using for most of the Eclipse development for OSATE.

However, recently, I wanted to build my own EObject instances and serialize them into a string to eventually write them into a file. Damned, this was pretty hard and after googl’ing a lot, I did not find a solution. After digging into the Eclipse TMF forum for a while, the TMF folks helped me and I got a code working.

I think it might be useful to share that since serializing an eobject can be something of particular interest for everybody (well, this is something you do every day, no?)

There is the code example, hope it could help some folks!

 

EObject myEobject;
/*
... create your eobject using your language
*/
Resource res = set.createResource(URI.createURI("foobar.mydsl"));
/*
 * Here, we create a fake resource that will contain the eobject.
 * This might be useful for the serializer.
 */
res.getContents().add(reqSpecModel);
/* We add the EObject to the fake resource */
IResourceServiceProvider rsp = IResourceServiceProvider.Registry.INSTANCE.getResourceServiceProvider(URI.createURI("fake.mysdsl"));
ISerializer serializer = rsp.get(ISerializer.class);
String s = serializer.serialize(myEobject);
/* Serialize the EObject */

InputStream stream = new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8));
newFile.create(stream, true, new NullProgressMonitor());
/* Write the EObject into a file */
Advertisements
How to serialize an EObject from Xtext

2 thoughts on “How to serialize an EObject from Xtext

  1. Well, I tried before and serialized the XMI, not the DSL itself, it was kind of weird! I guess that it did not pick the right serializer because there was some issue in my code for sure !

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s