简体   繁体   English

尝试使用jackson在java中将平面yaml文件转换为hashmap

[英]Trying to convert flat yaml file into hashmap in java using jackson

I'm trying to convert a flat yaml file which looks like this我正在尝试转换一个看起来像这样的平面 yaml 文件

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.如果我不必向 pojo 添加属性,我更愿意,因为这对我来说是更多的维护。 Any example of how this would be done with jackson?杰克逊如何做到这一点的任何例子?

I ended up using a yaml file like this:我最终使用了这样的 yaml 文件:

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:像这样的 pojo:

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.希望能帮助某人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM