简体   繁体   中英

How to quickly convert java / json to Xtext langauge?

I am working on an app that processes incoming Json's and I want to easily extract the json data and convert it to a DSL language I'v created using Xtext. My goal is to be able to later convert this data to a String that is based on my. I could probably just extract the data and manually add it to a big String variable,but I want to do this programmatically. So,does Xtext supports that. Is there any way to convert data to an Xtext object and later to a String (I am looking for something like json object classes)

Thanks!

If I correctly understand your question, you have already created an Xtext grammar that syntactically 'looks like' JSON.

In that case, the Xtext generated parser will be able to parse documents that follow the grammar specification (meaning they are both valid JSON and valid according to the grammar of your language).

The code that you would write looks as follows:

Package org.something.other

import com.google.inject.Injector;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.xtext.resource.XtextResourceSet;
import org.YourDSL.YourDSLStandaloneSetupGenerated;

public class ParseDocument {

    public static void main(String[] args) throws IOException {
    //First you use dependency injection to register the generated resource factory with EMF
    Injector injector = new ourDSLStandaloneSetupGenerated().createInjectorAndDoEMFRegistration();
    //Get a resource set object 
    XtextResourceSet resourceSet = injector.getInstance(XtextResourceSet.class);
    //Register the generated EMF package
    resourceSet.getPackageRegistry().put
        (YourDSLPackage.eNS_URI, YourDSLPackage.eINSTANCE);
    //Create an new resource with a suitable URI
    Resource resource = 
    resourceSet.getResource(URI.createFileURI("./test.yourdsl"), true);
    //You can now programmatically query and manipulate objects according to the metamodel of you DSL
    MainClass root = (MainClass)resource.getContents().get(0);
    }

That being said, an Xtext parser might be complete overkill depending on what you are trying to do and something like Jackson might be a better fit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM