简体   繁体   English

如何快速将java / json转换成Xtext语言?

[英]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.我正在开发一个处理传入 Json 的应用程序,我想轻松提取 json 数据并将其转换为我使用 Xtext 创建的 DSL 语言。 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.那么,Xtext 支持吗? 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)有什么方法可以将数据转换为 Xtext object 然后再转换为字符串(我正在寻找类似 json object 类的东西)

Thanks!谢谢!

If I correctly understand your question, you have already created an Xtext grammar that syntactically 'looks like' JSON.如果我正确理解了您的问题,那么您已经创建了一个语法上“看起来像”JSON 的 Xtext 语法。

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).在这种情况下,Xtext 生成的解析器将能够解析遵循语法规范的文档(这意味着它们都是有效的 JSON 并且根据您的语言的语法有效)。

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.话虽如此,根据您要执行的操作,Xtext 解析器可能完全矫枉过正,而 Jackson 之类的解析器可能更合适。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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