前言:
目前需要做一个将游戏基础数据抽取到配置文件中,然后每次初始化项目就根据配置文件初始化游戏的基础数据,因为之前用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());
}
}