Skip to content

Commit

Permalink
修复Json读取的bug
Browse files Browse the repository at this point in the history
  • Loading branch information
MrCraftGoo committed Feb 15, 2020
1 parent 465ef65 commit 4544aa8
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
18 changes: 14 additions & 4 deletions src/main/java/xyz/hstudio/hstudiolibrary/json/JsonUtils.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package xyz.hstudio.hstudiolibrary.json;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.bukkit.plugin.Plugin;
Expand All @@ -12,11 +14,19 @@

public class JsonUtils {

/**
* 自动加载Json文件
*
* @param plugin 插件实例
* @param instance Json类实例
* @param file Json文件
*/
public static <T> T load(final Plugin plugin, final T instance, final File file) {
if (!file.exists()) {
throw new IllegalStateException("文件 " + file.getName() + " 不存在!");
}
try {
Gson gson = new Gson();
JsonObject element = new JsonParser().parse(new FileReader(file)).getAsJsonObject();
// 遍历所有成员
for (Field field : instance.getClass().getDeclaredFields()) {
Expand All @@ -27,18 +37,18 @@ public static <T> T load(final Plugin plugin, final T instance, final File file)
if (annotation == null) {
continue;
}
String[] paths = annotation.path().split(".");
String[] paths = annotation.path().contains(".") ? annotation.path().split("\\.") : new String[]{annotation.path()};

Object value = null;
JsonElement value = null;
for (String path : paths) {
value = element.getAsJsonObject(path);
value = value == null ? element.get(path) : value.getAsJsonObject().get(path);
}

if (value == null) {
throw new IllegalStateException("没有找到文件 " + file.getName() + " 值 " + field.getName() + " !");
}

field.set(instance, value);
field.set(instance, gson.fromJson(value, field.getType()));
} catch (IllegalAccessException e) {
throw new IllegalStateException("加载文件 " + file.getName() + " 值 " + field.getName() + " 时出现错误!");
} finally {
Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/plugin.yml
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
name: HStudioLibrary
main: xyz.hstudio.hstudiolibrary.HStudioLibrary
version: '1.0.2'
version: '1.0.3'

0 comments on commit 4544aa8

Please sign in to comment.