Reputation: 217
I'm trying to convert a flat yaml file which looks like this
aramex: "Aramex"
aramex_cash_on_delivery: "Aramex COD"
australia_post: "Australia Post"
boxberry_delivery: "Boxberry Delivery"
boxberry_locker: "Boxberry Pickup and Postamats"
boxit_delivery: "BoxIt Home Delivery"
boxit_locker: "BoxIt Locker & Store Pickup"
chronopost: "Chronopost"
into a hashmap so I can access it from the keys directly without having to to maintain additional files.
such as:
map.get("aramex"); // should return "Aramex"
I would prefer if I didn't have to add properties to a pojo because that is more maintenance for me. Any example of how this would be done with jackson?
Upvotes: 1
Views: 579
Reputation: 217
I ended up using a yaml file like this:
shipping_options:
aramex: "Aramex"
aramex_cash_on_delivery: "Aramex COD"
australia_post: "Australia Post"
boxberry_delivery: "Boxberry Delivery"
boxberry_locker: "Boxberry Pickup and Postamats"
A pojo like this:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ShippingOptions {
@JsonProperty("shipping_options")
Map<String, String> shippingOptions;
}
And code to get the key:
public static String getShippingOptionValue(String key) throws IOException {
String baseDir = System.getProperty("user.dir");
String filePath = baseDir + "/src/test/resources/shippingoptions.yaml";
File yaml = new File(filePath);
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
mapper.findAndRegisterModules();
ShippingOptions shippingOptions = null;
try {
shippingOptions = mapper.readValue(yaml, ShippingOptions.class);
} catch (FileNotFoundException e) {
log.info("file could not be found {}", filePath);
} catch (IOException e) {
log.info("could not load shipping options from {}", filePath);
throw new IOException("shipping options YAML file was unable to be converted by Jackson {}", e);
}
assert shippingOptions != null;
String value = shippingOptions.getShippingOptions().get(key);
log.info("Shipping option retrieved was {}", value);
}
Hope that helps someone.
Upvotes: 1