After some mapping that ́s out of my control, I receive and Object that looks like this: enter image description here
This is how I ́m getting this Object, from the original message
Object valueArray = x.getFieldData().getData().getAdditionalProperties().get("items");
I need to get the value out of each element, do some basic math operations, and update the original message. If it ́s not an array I don ́t really have a problem, but I can ́t seem to in this case. This is how I ́m doing it for non arrays:
Object value = x.getFieldData().getData().getAdditionalProperties().get("value");
if(value != null){
Double result = (Double) value * Double.parseDouble(rule.values.get(0));
x.getFieldData().getData().getAdditionalProperties().put("value", result);
}
Any ideas on how to approach this? Thank you
1 Answer 1
It kind of depends on how your data is documented. You have to typecast everything staying safe, and for that you need to make some assumptions:
if (valueArray instanceof List) {
@SuppressWarnings("unchecked") // <- need a type in List declaration rather than '?' to allow for List.set, 'Object' being safe
List<Object> valueList = (List<Object>) valueArray;
for (int i = 0; i < valueList.size(); i++) {
Object val = valueList.get(i);
if (val instanceof Map) {
@SuppressWarnings("unchecked") // <- you need to be sure that all keys are strings to do that, otherwise use <Object, Object> and typecast again as needed
Map<String, Object> mVal = (Map<String, Object>) val;
//Do something with you map, e.g. change some value:
mVal.put("myprop", "a-value");
}
//Or change the value entirely, e.g.:
valueList.set(i, new LinkedHashMap<String, Object>());
}
}
Note that instanceof
checks also check for null
.
Now if you're 100% guaranteed that the read object is always a java.util.List
(as ArrayList
is) of java.util.Map
(LinkedHashMap
is a subclass of Map
) with keys of type String
, you can simplify to this:
if (valueArray instanceof List) {
@SuppressWarnings("unchecked") // <- need to be 100% sure of all types involved every time: UNSAFE operation!
List<Map<String, Object>> valueList = (List<Map<String, Object>>) valueArray;
for (int i = 0; i < valueList.size(); i++) {
Map<String, Object> val = valueList.get(i);
if (val != null) {
//Do something with you map, e.g. change some value:
val.put("myprop", "a-value");
}
//Or change the value entirely, e.g.:
valueList.set(i, new LinkedHashMap<String, Object>());
}
}
-
Thanks a lot, this is what I was looking for! On the long run I probably will ask the other team to send the data better structured, but for now this works.JuanjoC– JuanjoC07/01/2021 11:39:40Commented Jul 1, 2021 at 11:39
valueArray
to anArrayList
and iterate through it...valueArray instanceof List
or maybe evenvalueArray instance of Iterable
and cast accordingly. However, it's still not clear to me what level of the hierarchy you are struggling with. Is it the list containting the nested map? Or is it the "labels" list inside the map?