Drools 6.2 如何在声明的类型中使用 ArrayList?

Drools 6.2 How to use ArrayList in declared types?

这是我的 DLR 文件中的内容:

package mytypes;

declare Person
    firstName : String
    lastName : String    
    address : java.util.ArrayList
end

declare Address
    city : String
    state : String
end

rule "city"
when 
 p : Person()
 Address(city == "Dallas") from p.address
then
System.out.println("city rule fired");
end

我使用 gson 将我的 json 转换为使用 FactType 的 Person 类型的 ojbect。见下文:

    FactType ft  = base.getFactType( "mytypes","Person" );
    Object oPerson = ft.newInstance();      
    Gson gConverter = new Gson();
    Object input = gConverter.fromJson(fact, oPerson.getClass());

这是我的 json:

{"firstName":"John","lastName":"Smith","address":[{"city":"Dallas","state":"TX"}]}

我把东西拿回来了。这是它在内存中的样子:

Person( firstName=John, lastName=Smith, address=[{city=Irving, state=TX}] )

我的规则没有被触发,因为如您所见,address 集合中没有 Address 类型。有谁知道如何让它工作?

或者,如果我不使用 json 获取 Person 对象,而是使用 "getFactType" 手动构建它并使用 "set" 设置属性,那么我可以获取我的规则被解雇。这是我手动构建它的方法

    FactType ftPerson  = base.getFactType( "mytypes","Person" );
    Object oPerson = ft.newInstance();
    ArrayList al = new ArrayList();
    FactType ftAddress  = base.getFactType( "mytypes","Address" );
    Object add = ftAddress.newInstance();
    ftAddress.set(add, "city", "Dallas");
    ftAddress.set(add, "state", "TX");
    al.add(add);
    ftPerson.set(oPerson, "address", al);

这是 Person 对象在内存中的样子,注意 Address 类型是如何在 address collection:

中指定的
Person( firstName=null, lastName=null, address=[Address( city=Irving, state=TX )] )

我希望我已经解释了完整的场景。我怎样才能继续使用 json 并使其正常工作?

由于ArrayList是一个泛型集合,Gson在处理JSON字符串时无法正确识别地址对象的类型。完成您正在尝试做的事情的最简单方法是使用数组而不是 ArrayList:

declare Person
  firstName : String
  lastName : String    
  address : Address[]
end

在那种情况下,Gson 应该正确地选择类型并且规则将会触发。