Google Gson を使用できる場合は、次の方法で実行できます。
プログラム.クラス
public class Program {
private String id;
private String title;
private String description;
public Program(String id, String title, String description) {
this.id = id;
this.title = title;
this.description = description;
}
@Override
public String toString() {
return String.format("Program[id=%s, title=%s, description=%s]", this.id, this.title, this.description);
}
}
ProgramsDeserializer.class
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
class ProgramsDeserializer implements JsonDeserializer<List<Program>> {
@Override
public List<Program> deserialize(JsonElement e, Type type, JsonDeserializationContext jdc) throws JsonParseException {
List<Program> programs = new ArrayList<>(10);
JsonObject root = e.getAsJsonObject();
for (Map.Entry<String, JsonElement> entry : root.entrySet()) {
String id = entry.getKey();
String title = "";
String description = "";
JsonElement arrayElement = entry.getValue();
if (arrayElement.isJsonArray()) {
JsonArray array = arrayElement.getAsJsonArray();
JsonElement objectElement = array.get(0);
if (objectElement.isJsonObject()) {
JsonObject object = objectElement.getAsJsonObject();
title = object.get("t").getAsString();
description = object.get("d").getAsString();
}
}
programs.add(new Program(id, title, description));
}
return programs;
}
}
GsonExample.class
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class GsonExample {
private static final Logger logger = Logger.getLogger(GsonExample.class.getName());
private static final String JSON =
"{"
+ "\"2002\": ["
+ "{"
+ "\"d\": \"description\","
+ "\"t\": \"title\""
+ "}"
+ "],"
+ "\"2003\": ["
+ "{"
+ "\"d\": \"description\","
+ "\"t\": \"title\""
+ "}"
+ "]"
+ "}";
public static void main(String[] args) {
GsonExample e = new GsonExample();
e.run();
}
private void run() {
GsonBuilder builder = new GsonBuilder();
Type type = new TypeToken<List<Program>>(){}.getType();
builder.registerTypeAdapter(type, new ProgramsDeserializer());
Gson gson = builder.create();
List<Program> programs = gson.fromJson(JSON, type);
logger.log(Level.INFO, "{0}", programs);
}
}