JAVA-yaml基本操作工具类

yaml基本操作工具类
public class YamlUtils {

    private static final Logger logger = LoggerFactory.getLogger(YamlUtils.class);

    /**
     * 导出yaml时无论有没有值都忽略的属性
     **/
    private final static ImmutableList<String> IGNORE_PROPERTIES_WHEN_DUMP_YAML = ImmutableList.of("resourceVersion");

    private static Yaml yaml;

    static {
        initYaml();
    }

    /**
     * 初始化Yaml
     */
    private static void initYaml() {
        DumperOptions options = new DumperOptions();
        options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
        options.setPrettyFlow(true);

        yaml = new Yaml(new Representer() {
            @Override
            protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, Tag customTag) {
                // 如果属性为null空数组,忽略它
                boolean beIgnored = (propertyValue instanceof Collection && ((Collection<?>) propertyValue).size() == 0);
                if (propertyValue == null || beIgnored) {
                    return null;
                } else {
                    if (IGNORE_PROPERTIES_WHEN_DUMP_YAML.contains(property.getName())) {
                        return null;
                    }
                    return super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
                }
            }
        }, options);
    }

    /**
     * javabean转yaml字符串
     *
     * @param resource 对象
     * @return String
     */
    public static String convertToYaml(Object resource) {
        return yaml.dump(resource);
    }

    /**
     * javabean导出成yaml文件
     *
     * @param resource 资源名称
     * @param filePath 文件路径
     */
    public static void dumpToYaml(Object resource, String filePath) {
        try (Writer writer = new FileWriter(filePath)) {
            yaml.dump(resource, writer);
        } catch (IOException e) {
            logger.error("[k8s][YamlUtils]dumpToYaml error:", e);
        }
    }

    /**
     * 转换成Yml格式字符串
     *
     * @param obj KubernetesResource对象
     * @return yml格式字符串
     */
    public static String dumpAsYaml(HasMetadata obj) {
        try {
            return SerializationUtils.dumpAsYaml(obj);
        } catch (JsonProcessingException e) {
            logger.error("[k8s][YamlUtils] dumpAsYaml error:", e);
        }
        return SymbolConstant.BLANK;
    }
}
SerializationUtils
public class SerializationUtils {

  private static ObjectMapper mapper;

  private static ObjectMapper statelessMapper;



  public static ObjectMapper getMapper() {
    if (mapper == null) {
      mapper = new ObjectMapper(new YAMLFactory());
    }
    return mapper;
  }

  public static String dumpAsYaml(HasMetadata obj) throws JsonProcessingException {
    return getMapper().writeValueAsString(obj);
  }


}

猜你喜欢

转载自blog.csdn.net/caryeko/article/details/141321397