commercetools / commercetools-sdk-java-v2

The e-commerce SDK from commercetools for Java.
https://commercetools.github.io/commercetools-sdk-java-v2/javadoc/index.html
Apache License 2.0
35 stars 15 forks source link

Question: How to get concrete typed attribute? #233

Closed pintomau closed 2 years ago

pintomau commented 2 years ago

Hi!

SDK1 had the feature of getting a typed attribute via the attribute.getValueAsX.

SDK2 seems to return an Object type value only.

Is there, within SDK2, a way to get the attribute in the concrete deserialized type? Or would this be a new feature within SDK2?

image

Thanks.

jenschude commented 2 years ago

No and yes :)

No atm there is no helper method for getting a specific attribute as a specific type as like as in the v1.

Yes there are possibilities to do so. The Attributes are already correctly deserialized only the return type is Object as this is the least common denominator for an attribute value. We added an AttributeAccessor which can help accessing the attributes e.g. by name. See

https://github.com/commercetools/commercetools-sdk-java-v2/blob/9f86dae350b89ad5ab00c0b9f9dbceefa91afaa6/commercetools/commercetools-sdk-java-api/src/test/java/com/commercetools/AttributesTest.java#L37-L46

This accessor comes also with some other small helpers methods.

https://github.com/commercetools/commercetools-sdk-java-v2/blob/9f86dae350b89ad5ab00c0b9f9dbceefa91afaa6/commercetools/commercetools-sdk-java-api/src/main/java/com/commercetools/api/product/AttributeAccessor.java#L15

We may introduce also an accessor which allows to retrieve a specific attribute by name and type. But atm you would have to build such an accessor by yourself.

Btw every model comes with an with<Model> method to apply an accessor, so this could also be done on the attribute level e.g.:

Map<String, Attribute> attributes = variant.withProductVariant(AttributeAccessor::asMap);
attributes.get("text").withAttribute(attribute -> (String)attribute.getValue());
attributes.get("ltext").withAttribute(attribute -> (LocalizedString)attribute.getValue());
jenschude commented 2 years ago

I added now the other accessor methods to get type safe values

https://github.com/commercetools/commercetools-sdk-java-v2/blob/7e7a98b3f4f55714690914109e36414f8d920ec1/commercetools/commercetools-sdk-java-api/src/main/java/com/commercetools/api/product/AttributeAccessor.java

Here you can see how to use them:

https://github.com/commercetools/commercetools-sdk-java-v2/blob/7e7a98b3f4f55714690914109e36414f8d920ec1/commercetools/commercetools-sdk-java-api/src/test/java/com/commercetools/AttributesTest.java#L237-L247

Will be available with the next release

pintomau commented 2 years ago

Alright, I see, interesting. Thanks for the additions.