[英]How to quickly convert java / json to Xtext langauge?
我正在開發一個處理傳入 Json 的應用程序,我想輕松提取 json 數據並將其轉換為我使用 Xtext 創建的 DSL 語言。 我的目標是以后能夠將此數據轉換為基於我的字符串。 我可能只提取數據並手動將其添加到一個大字符串變量中,但我想以編程方式執行此操作。 那么,Xtext 支持嗎? 有什么方法可以將數據轉換為 Xtext object 然后再轉換為字符串(我正在尋找類似 json object 類的東西)
謝謝!
如果我正確理解了您的問題,那么您已經創建了一個語法上“看起來像”JSON 的 Xtext 語法。
在這種情況下,Xtext 生成的解析器將能夠解析遵循語法規范的文檔(這意味着它們都是有效的 JSON 並且根據您的語言的語法有效)。
您要編寫的代碼如下所示:
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);
}
話雖如此,根據您要執行的操作,Xtext 解析器可能完全矯枉過正,而 Jackson 之類的解析器可能更合適。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.