假设我有一个像这样的json文件:
{
"ObjectName1": {
"enabled": true,
"SSOIDS": []
},
"ObjectName2": {
"enabled": true,
"SSOIDS": []
},
"ObjectName3": {
"enabled": true,
"SSOIDS": []
},
"ObjectName4": {
"enabled": true,
"IDs": []
}
}
我想对数据进行去磁化并将“ObjectNameX”存储到我的Java对象的字段objectName中,例如:
public class Feature implements Serializable {
private static final long serialVersionUID = 1L;
private String objectName;
private Boolean enabled;
private List<String> IDs;
private boolean checkLastTwoChars; //sometimes my json objects might have this
//element.However in this example it doesn't
//Getters and Setters left out for brevity
我已经阅读了一些关于创建自定义反序列化程序here的内容 并创建了以下类:
public class FeatureDeserializer implements JsonDeserializer<Feature> {
public Feature deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
Feature ft = new Feature();
if(!json.isJsonNull()){
ft.setFeatureName(json.getAsJsonObject().getAsString());
//json.getAsJsonObject().getAsString()--> `{"enabled":true,"SSOIDS":[],"checkLastTwoChars":false}
}
return ft;
}
}
但是反序列化器中的json参数在运行时无法访问objectNameX,即只有objet字段的键值对可用。 我知道GSON正在反序列化正确的值,并且可以从eclipse调试器访问objectNameX。
以下是我调用fromJson()的方法:
// just the part I think is relevant
Map<String, Feature> featureCache = new HashMap<String, Feature>();
for(File file : files){
try {
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuilder sb = new StringBuilder();
while(br.ready()){
sb.append(br.readLine());
}
br.close();
Gson gson = new GsonBuilder().setPrettyPrinting().
registerTypeAdapter(Feature.class, new FeatureDeserializer()).create();
featureCache = gson.fromJson(sb.toString(), new TypeToken<SortedMap<String, Feature>>(){}.getType()); // features in a specific file
在我反序列化的每个唯一对象中是否存在保存每个objectNamex的标准方法?
答案 0 :(得分:0)
这是我解决在每个反序列化的唯一对象中保存每个objectNamex的问题的解决方案,但是我仍然不确定这是否是最好的甚至是常见的做法。
我意识到:
Gson gson = new GsonBuilder().setPrettyPrinting().
registerTypeAdapter(Feature.class, new FeatureDeserializer()).create();
featureCache = gson.fromJson(sb.toString(), new TypeToken<SortedMap<String, Feature>>(){}.getType()); // features in a specific file
实际上是创建一个mapName,因为objectNamex是每个唯一Feature对象的键,因此
我创建了一个辅助函数:
private void fillInFeatureNames(Map<String, Feature> featureCache){
for (String featName: featureCache.keySet()){
featureCache.get(featName).setFeatureName(featName);
}
}
循环遍历地图中的每个键,并将每个唯一要素对象featureName字段设置为键名。这是一个有效的工作,但我仍然想知道这项工作是否有一个首选的做法。