That's what I ended up doing, many thanks.
I will put my code below in case it can help somebody else.
P.S: for people looking to do the same thing, I still think the batch
executor helper is the best way to tackle this need, as we would not need to
rewrite the part that converts objects to/from Json. Please check the other
part of the thread with Mark to see if we manage to find the right syntax.
best regards,
private static String retreiveFacts(ArrayList facts,
KnowledgeBase kBase, StatefulKnowledgeSession session)
throws JSONException {
JSONObject resultArray = new JSONObject();
JSONArray objects = new JSONArray();
resultArray.put("objects", objects);
for (Iterator iterator = facts.iterator(); iterator.hasNext();) {
Object fact = iterator.next();
JSONObject object = new JSONObject();
object.put("object", fact.getClass().getCanonicalName());
JSONObject fields = new JSONObject();
FactType objectType = kBase.getFactType(fact.getClass()
.getPackage().getName(), fact.getClass().getSimpleName());
for (FactField field : objectType.getFields()) {
fields.put(field.getName(),
objectType.get(fact, field.getName().toString()));
}
object.put("fields", fields);
objects.put(object);
}
return resultArray.toString();
}
private static ArrayList insertFacts(JSONObject json,
KnowledgeBase kBase, StatefulKnowledgeSession session)
throws IOException, JSONException, InstantiationException,
IllegalAccessException {
ArrayList handlers = new ArrayList();
JSONArray objects = (JSONArray) json.get("objects");
for (int i = 0; i < objects.length(); i++) {
JSONObject object = objects.getJSONObject(i);
String objectCanonicalName = object.getString("object");
System.out.println(objectCanonicalName);
int classNameSeparatorIndex = objectCanonicalName.lastIndexOf(".");
String packageName = objectCanonicalName.substring(0,
classNameSeparatorIndex);
String className = objectCanonicalName
.substring(classNameSeparatorIndex + 1);
FactType objectType = kBase.getFactType(packageName, className);
Object factObject = objectType.newInstance();
JSONObject fields = object.getJSONObject("fields");
for (Iterator iterator = fields.keys(); iterator.hasNext();) {
String key = (String) iterator.next();
System.out.println("field " + key + " value "
+ fields.get(key));
objectType.set(factObject, key, fields.get(key));
}
session.insert(factObject);
handlers.add(factObject);
}
return handlers;
}
--
View this message in context:
http://drools.46999.n3.nabble.com/Inserting-Facts-from-Json-Format-tp3570...
Sent from the Drools: User forum mailing list archive at
Nabble.com.