-
Notifications
You must be signed in to change notification settings - Fork 15
Using XCore
We can now create an Ecore model using the EMF dynamic API. It is also possible to use code generation to generate Java code from EMF models, for this look at other tutorials about EMF.
An Ecore model is made of EPackage that contains a collections of classes (EClass) that represent the kind of objects we will create in our documents.
We create a package that contains a single class named User. This class contains a single attribute, name
. This way we
will be able to create objects of type User
and assign them a name.
@Ecore(nsURI="http://emfjson.org/domain")
@GenModel(
)
package domain
class User {
String name
String email
}
class Comment {
String text
Date time
}
resourceSet.getPackageRegistry()
.put(EcorePackage.eNS_URI, EcorePackage.eINSTANCE);
resourceSet.getPackageRegistry()
.put(DomainPackage.eNS_URI, DomainPackage.eINSTANCE);
The result will be a JSON object representing our EPackage.
The next step will be to create an instance of the class User
. For that we will still use the EMF dynamic API.
To create a new instance from a EClass, use the utility class EcoreUtil.
User bob = DomainFactory.eINSTANCE.createUser();
bob.setName("Bob");
That's it, we created a dynamic instance of the class User. We can now set a value for the attribute name
.
This is done by using the method eSet
.
Before we can serialize this instance in JSON, we need to add it to a Resource, like we did previously.
Resource resource = resourceSet.createResource(URI.createURI("http://localhost:8080/users/bob"));
resource.getContents().add(bob);
And save it.
resource.save(null);
This will result in a single JSON object being our instance of User.
{
"eClass" : "http://emfjson.org/domain#//User",
"name" : "Bob"
}