Javaアプリケーションでテストデータを扱う際、JSONファイルをリソースディレクトリに配置し、それをJavaオブジェクトに変換する方法について説明します。
JSONファイル変換ユーティリティの実装
以下のユーティリティクラスは、リソースパスからJSONファイルを読み込み、指定されたクラス型に変換します。
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.io.IOException;
import com.alibaba.fastjson.JSON;
import org.apache.commons.io.IOUtils;
public class JsonResourceParser {
public static <T> T convertJsonToObject(String resourcePath, Class<T> targetClass) throws IOException {
InputStream fileStream = JsonResourceParser.class.getResourceAsStream(resourcePath);
if (fileStream == null) {
throw new IOException("指定されたリソースファイルが見つかりません: " + resourcePath);
}
String jsonContent = IOUtils.toString(fileStream, StandardCharsets.UTF_8);
return JSON.parseObject(jsonContent, targetClass);
}
public static <T> ArrayList<T> convertJsonToCollection(String resourcePath, Class<T> elementClass) throws IOException {
InputStream fileStream = JsonResourceParser.class.getResourceAsStream(resourcePath);
if (fileStream == null) {
throw new IOException("指定されたリソースファイルが見つかりません: " + resourcePath);
}
String jsonContent = IOUtils.toString(fileStream, StandardCharsets.UTF_8);
return new ArrayList<>(JSON.parseArray(jsonContent, elementClass));
}
}
JSONファイルの例
単一オブジェクト用JSONファイル (student.json):
{
"id": "S001",
"name": "田中太郎",
"grade": 2
}
コレクション用JSONファイル (students.json):
[
{
"id": "S001",
"name": "田中太郎",
"grade": 2
},
{
"id": "S002",
"name": "鈴木花子",
"grade": 3
}
]
ユーティリティの使用方法
import java.io.IOException;
import java.util.ArrayList;
public class JsonConversionExample {
public void convertSingleObject() throws IOException {
String resourceLocation = "/data/students/student.json";
Student student = JsonResourceParser.convertJsonToObject(resourceLocation, Student.class);
System.out.println("変換結果: " + student.toString());
}
public void convertObjectCollection() throws IOException {
String resourceLocation = "/data/students/students.json";
ArrayList<Student> studentList = JsonResourceParser.convertJsonToCollection(resourceLocation, Student.class);
System.out.println("リストサイズ: " + studentList.size());
}
}
注意点: リソースパスは絶対パス("/"で始まる)で指定する必要があります。相対パスを使用するとファイルが見つからない場合があります。