基于snakeyaml读取yml配置文件生成JAVA复杂对象

前言:

目前需要做一个将游戏基础数据抽取到配置文件中,然后每次初始化项目就根据配置文件初始化游戏的基础数据,因为之前用springboot比较多,对于yml的书写格式比较熟悉。可以轻松的构造出类的结构。然后在网上搜索了一会儿基本都是一些基础数据的读取、或者是基于springboot注解读取。这里记录一下读取解析集合类型和复杂类型的对象的过程。

准备

  <dependency>
            <groupId>org.yaml</groupId>
            <artifactId>snakeyam`</artifactId>
            <version>1.26</version>
    </dependency>

例子

实体类
public class BaseMessage {
    List<SceneMessage> sceneMessages;
    List<NPCMessage> npcMessages;
//getter & setter
}
public class SceneMessage {
    private Integer id;
    private String placeName;
    private String canScene;
    //getter & setter
}
public class NPCMessage {
    private Integer id;
    private Integer status;
    private String name;
    private Integer type;
    private Integer mmosceneid;
    private Integer onstatus;
     //getter & setter
}
配置文件
sceneMessages:
  - id: 1
    placeName: "森林"
    canScene: 2
  - id: 2
    placeName: "村子"
    canScene: 1,3
npcMessages:
  - id: 1
    name: "时王zio"
    mmosceneid: 1
    status: 1
    type: 1
    onstatus: 9527
  - id: 1
    name: "假面build"
    mmosceneid: 1
    status: 1
    type: 1
    onstatus: 9527
Main函数
public class YmlUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(YmlUtils.class);

    private static String bootstrap_file = "classpath:baseMessage.yaml";

    public static void main(String[] args) throws FileNotFoundException {
        InputStream in = null;
        File file = ResourceUtils.getFile(bootstrap_file);
        in = new BufferedInputStream(new FileInputStream(file));
        Yaml props = new Yaml(new Constructor(BaseMessage.class));
        BaseMessage obj = props.load(in);
        System.out.println(obj.getSceneMessages().get(1).toString());
    }
}
运行结果

在这里插入图片描述

参考

snakeyaml的github仓库

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值