如何解决如何更新Azure DeviceTwin NESTED所需的属性? Java
我正在使用com.microsoft.azure.sdk.iot:iot-service-client:1.16.0
库(Java)与Azure IoT设备一起使用。我正在尝试“更新”一些属性,但是它们嵌套了,我在更新它们时遇到了麻烦。
我的DeviceTwin Json看起来像这样:
azure库带有setDesiredProperties
函数,该函数以HashSet<Pair>
作为参数。因此,我可以轻松更新`firmwareVersionToDownload”,“ serverConfigurationVersion”或“ webContentDataType”键,因为它们是顶级实体,如下所示(如上图所示):
myIotDeviceObjectInJava.setDesiredProperties(new HashSet<Pair>() {{
add(new Pair("myKey","myNewValueForKey"));
}});
我需要将键“ object1”和“ object2”的值设置为“ null”的值,但它们的深度为2/3级。谁能帮我做到这一点?
我尝试与其他嵌套的HashSet创建一个新的HashSet,直到达到第三个级别,然后再传递一个新的Pair(“ object1”,“ null”)对象设置为null,但是最终只需删除我的整个"serverConfiguration"
代码块(下面的示例):
updateProperties(new HashSet<Pair>() {{
add(new Pair("serverConfiguration",new HashSet<Pair>() {{
add(new Pair("nestedIpData1",new HashSet<Pair>() {{
add(new Pair("object1","null"));
}}));
}}));
}}
);
我是否需要遍历顶级对象并获取serverConfiguration
的值对象,然后以这种方式进行设置?
解决方法
我继续尝试使用示例Get started with device twins (Java),并在Service App中进行了一些调整。
注意:我使用了com.microsoft.azure.sdk.iot:iot-service-client:1.25.0
为了理解在读取带有嵌套Json对象的所需属性时返回的对象类型,我首先直接在Azure门户中编辑了Twin,然后调试了代码以检查ojbect的类型:
DeviceTwin twinClient = DeviceTwin.createFromConnectionString(iotHubConnectionString);
DeviceTwinDevice device = new DeviceTwinDevice(deviceId);
Set<Pair> currentDesired = device.getDesiredProperties();
您会注意到“ ServerConfiguration”和“ Object3”值的类型为TwinCollection(请检查TwinCollection.java代码注释以更好地理解它)
因此,为了将object1和object 2设置为null:
TwinCollection nestedIpData1 = new TwinCollection();
TwinCollection object1 = new TwinCollection();
TwinCollection object2 = new TwinCollection();
TwinCollection object3 = new TwinCollection();
object1.putFinal("hostname","my.host.name1");
object1.putFinal("netmask","1.1.1.1");
object1.putFinal("ip","1.1.1.1");
object1.putFinal("cloudIp","1.1.1.1");
object1.putFinal("gateway","1.1.1.1");
object2.putFinal("hostname","my.host.name2");
object2.putFinal("netmask","2.2.2.2");
object2.putFinal("ip","2.2.2.2");
object2.putFinal("cloudIp","2.2.2.2");
object2.putFinal("gateway","2.2.2.2");
object3.putFinal("hostname","my.host.name3");
object3.putFinal("netmask","3.3.3.3");
object3.putFinal("ip","3.3.3.3");
object3.putFinal("cloudIp","3.3.3.3");
object3.putFinal("gateway","3.3.3.3");
nestedIpData1.putFinal("object1",null);
nestedIpData1.putFinal("object2",null);
nestedIpData1.putFinal("object3",object3);
Set<Pair> desiredProperties = new HashSet<Pair>();
desiredProperties.add(new Pair("serverConfiguration",nestedIpData1));
device.setDesiredProperties(desiredProperties);
// Update the device twin in IoT Hub
System.out.println("Updating device twin with nestedobject");
twinClient.updateTwin(device);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。