To convert javascript to java object I use this function:
public <T> T toObject(String js, Class<T> classToReturn) throws ScriptException, JsonMappingException, JsonProcessingException {
final ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("JavaScript");
scriptEngine.eval("variable = " + js);
scriptEngine.eval("json= JSON.stringify(variable);");
final String json = (String) scriptEngine.get("json");
final ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return mapper.readValue(json, classToReturn);
}
Example:
final String js = "[{name:'FieldName', numbers: [1,2,3], strings: ['one','two','three'], innerClass:[{name:'InnerClass1', numbers: [4,5,6]},{name:'InnerClass2', strings: ['test']}]}, {strings: ['asdasda','tsdsdf']}]";
final ClassToGet[] objects = toObject(js, ClassToGet[].class);
Class to get:
@Getter @Setter @ToString
public class ClassToGet{
private String name;
private int[] numbers;
private List<String> strings;
private Set<ClassToGet> innerClass;
}