如何在 Java SDK 中访问 c8y_PropertyType(自定义属性)?

How to access c8y_PropertyType (custom attributes) in Java SDK?

我正在使用 Cumulocity Java SDK,我正在尝试访问 ManagedObject 之一中的自定义片段。类似的东西:

...
"type": "sap_CustomomerLocation",
"c8y_PropertyType":{
    "Customer.Name":{ 
        "name":"customerName", 
        "sap_field_name":{
            "requestIdentifier":"SAP",
            "adressIdentifier":"customerName" 
        }
    },
    "Customer.Address":{ 
        "name":"customerAddress", 
        "sap_field_name":{
            "requestIdentifier":"SAP",
            "adressIdentifier":"customerAddress" 
        }
    }
}
...

我无法更改片段的格式。在 Java 应用程序中,我通过以下方式获取 Mo:

InventoryFilter filter = new InventoryFilter();
filter.byType("sap_CustomomerLocation");

ManagedObjectCollection configuration = platform.getInventoryApi().getManagedObjectsByFilter(filter);
ManagedObjectRepresentation singleConfig = configuration.get().allPages().iterator().next();

Map<String, Object> attrs = singleConfig.getAttrs();

问题是我无法访问 "sap_field_name",attrs 是一个 HashMap@Node。在 IntelliJ 的调试器中,当我使用 "evaluateExpression" 时,会生成类似的东西:

((HashMap.Node)((HashMap)((HashMap.Node)((HashMap)((HashMap.Node)((HashMap)((HashMap.Node)((HashMap)attrs).entrySet().toArray()[0]).getValue()).entrySet().toArray()[0]).getValue()).entrySet().toArray()[0]).getValue()).entrySet().toArray()[1]).getValue()

那么,你能推荐点什么吗?我应该以某种方式将它投射到 DTO 吗?但是如何处理 JSON ("Customer.Name", "Customer.Address") 中的键可以更改,因为这是一个字段列表。

您可以采用的一种方法是为您的 c8y_PropertyType 片段创建一个与内容匹配的模型 class。要映射此片段,您需要在包 c8y 中创建一个 class PropertyType 并将其放在 class 路径上。

JSON 解析器应该不再生成此 HashMap 结构,而是生成您的 class。我不确定 JSON 键中的点是否会导致此处出现问题。

如果您需要此类 class 的示例,请检查 https://bitbucket.org/m2m/cumulocity-clients-java/src/03e47693b1d389308901347d224c13d81250b703/device-capability-model/?at=develop

我试图在命名空间 c8y.PropertyType 中创建一个新的 class 并且它有点工作,Cumulocity SDK,或者更确切地说 Jackson JSON 发现有一个 class 和试图映射它,但问题仍然存在于这个动态字段中。

在对 Jackson 代码进行少量调试后,我发现我需要在正确的命名空间中为所有自定义字段创建一个 class(不幸的是我不知道名称)。

所以这是我认为可以接受的解决方法:

ManagedObjectRepresentation singleConfig;

Map<String, Object> attrs = singleConfig.getAttrs();
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.valueToTree(attrs);

String customFieldName = jsonNode.get("c8y_PropertyType").get("attrs").iterator().next().get("sap_field_name").get("adressIdentifier").asText();