У меня есть следующий JSON записывается в файл, который я хочу прочитать через Gson:Gson разобрать объект JSON с родовым типом
{
"identifier": "CONFIG",
"data": [
{
"identifier": "HOTKEY",
"data": {
"hotKey": "testKey1",
"type": "APPLICATION",
"runnableContext": "testContext1"
}
},
{
"identifier": "HOTKEY",
"data": {
"hotKey": "testKey2",
"type": "APPLICATION",
"runnableContext": "testContext2"
}
}
]
}
В приведенных выше Json, вы можете увидеть, что конструкция данных Identifier & является рекурсивно повторяется. Таким образом, базовый класс, представляющий этот повторяющийся рисунок является родовым один, как показано ниже:
{
"identifier": "CONFIG",
"data": {
}
}
Эта модель представлена классом JsonData следующим образом:
import java.util.Set;
....
import com.google.common.collect.ImmutableSet;
/**
* Class representing a simple {@link JsonData#identifier},
* {@link JsonData#data} format. This class can be used to
* persist application data for example in a Configuration file.
*
* @author SW029693
* @since v1.0
*/
public class JsonData <T>{
/**
* Represents a unique identifier
*/
private String identifier;
/**
* Represents the data pertaining to this {@link JsonData#identifier}
*/
private T data;
private static final Set<String> VALID_JSON_ID_TYPES = ImmutableSet.of("CONFIG","HOTKEYS","HOTKEY","RECOMMENDATIONS");
public JsonData(String identifier, T data) {
super();
this.identifier = identifier;
this.data = data;
}
/**
* Getter for {@link JsonData#identifier}
* @return
*/
public String getIdentifier() {
return identifier;
}
/**
* Sets the {@link JsonData#identifier} to the given value
* @param identifier
* Represents a unique {@link JsonData#identifier}
* @throws VerifyException
* If the argument is {@code null} or {@code empty}
*/
public void setIdentifier(String identifier) throws VerifyException{
Verifier.verifyNotNull(identifier, "identifier : null");
Verifier.verifyNotEmpty(identifier,"identifier : empty");
this.identifier = identifier;
}
/**
* Getter for {@link JsonData}
* @return
*/
public T getData() {
return data;
}
/**
* Sets the {@link JsonData#data} to the given value
* @param identifier
* Represents a unique {@link JsonData#data}
* @throws VerifyException
* If the argument is {@code null}
*/
public void setData(T data) {
Verifier.verifyNotNull(data, "data : null");
this.data = data;
}
@Override
public String toString() {
return "JsonData [identifier=" + identifier + ", data=" + data + "]";
}
}
Кроме того, в Json выше, вы можете см. данные в каждой горячей клавише. Эти данные должны быть проведены в классе ConfigurationProperty после чтения json через gson:
public class ConfigurationProperty implements Comparable<ConfigurationProperty>, Serializable{
....
private final String hotKey;
private final String type;
private final String runnableContext;
....
Теперь вопрос. Я пытаюсь прочитать файл и проанализировать Json, чтобы сохранить его в соответствующие объекты с помощью GSON без везения.
У меня есть рабочий код для чтения одного объекта JsonData записывается в файл:
{
"identifier": "HOTKEY",
"data": {
"hotKey": "testKey1",
"type": "APPLICATION",
"runnableContext": "testContext1"
}
}
будет успешно прочитано:
private static JsonData<ConfigurationProperty> readconfigFile() {
Reader reader = null;
JsonData<ConfigurationProperty> data = null;
Gson gson = null;
Type confType;
try {
reader = new FileReader("./config.json");
gson = new GsonBuilder().create();
confType = new TypeToken<JsonData<ConfigurationProperty>>() {}.getType();
data = gson.fromJson(reader,confType);
} catch (FileNotFoundException e) {
e.printStackTrace();
fail("Test failed while reading the config.json file: "+e.getMessage()); }
finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
fail("Test failed while reading the config.json file: "+e.getMessage());
}
}
return data;
}
Но если вы посмотрите на первый JSON, это теперь рекурсивная структура JsonData. Также во время разбора мне нужно сообщить Gson, что первым объектом данных является ARRAY объектов JsonData. И мне также нужно сказать gson, что каждый объект JSONData в этом массиве имеет тип ConfigurationProperty.
Я не уверен, как это сделать.