如何使用 ParseHelper 从 DSL 解析为对象

How to parse from DSL to Object with ParseHelper

我想用 ParseHelper 解析写入 JsonObject 的 DSL 程序

public static JsonModel toJsonModel(CharSequence c) {
    ParseHelper<JsonModel> parseHelper = new ParseHelper<JsonModel>();
    try {
        return parseHelper.parse(c);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

public static void main(String args[]) {
    
    String chaine = "jsonValue { \"Nom\" : \"Toto\",\r\n"
            + "          \"Adresse\" : { \r\n"
            + "                      \"Adresse 1\" : \"x avenue de xx\",\r\n"
            + "                      \"Adresse 2\" : \" x rue de xx\"\r\n"
            + "                      },\r\n"
            + "         }\r\n"
            + "         filename = \"jsonFileToRead.json\"\r\n"
            + "         SearchForKey(\"xx\") in jsonValue\r\n";
    CharSequence c = "'''"+chaine+"'''";
    
    JsonModel model = toJsonModel(c);


}

但我似乎无法解析,出现以下错误:

java.lang.NullPointerException: Cannot invoke "org.eclipse.xtext.testing.util.ResourceHelper.createResourceSet()" because "this.resourceHelper" is null
at org.eclipse.xtext.testing.util.ParseHelper.parse(ParseHelper.java:65)
at org.istic.idm.tests.TempsMemoire.toJsonModel(TempsMemoire.java:14)
at org.istic.idm.tests.TempsMemoire.main(TempsMemoire.java:49)

您需要使用注入来获取解析助手,例如

import org.eclipse.xtext.testing.util.ParseHelper;
import org.xtext.example.mydsl5.MyDslStandaloneSetup;
import org.xtext.example.mydsl5.myDsl.Model;

import com.google.inject.Inject;
import com.google.inject.Injector;

public class Main {

    public static void main(String[] args) throws Exception {
        Injector injector = new MyDslStandaloneSetup().createInjectorAndDoEMFRegistration();
        Main main = injector.getInstance(Main.class);
        System.out.println(main.doGetModel("Hello World!"));

    }
    @Inject ParseHelper<Model> parserHelper;
    
    public Model doGetModel(String content) throws Exception {
        return parserHelper.parse(content);
    }

}

import org.eclipse.xtext.testing.util.ParseHelper;
import org.xtext.example.mydsl5.MyDslStandaloneSetup;
import org.xtext.example.mydsl5.myDsl.Model;

import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
    
public class Main {

    public static void main(String[] args) throws Exception {
        System.out.println(doGetModel("Hello World!"));

    }
    public static Model doGetModel(String content) throws Exception {
        Injector injector = new MyDslStandaloneSetup().createInjectorAndDoEMFRegistration();
        ParseHelper<Model> parserHelper = injector.getInstance(Key.get(new TypeLiteral<ParseHelper<Model>>() {}));
        return parserHelper.parse(content);
    }

}