@Kedar
我假设您控制着JSON输入字符串的创建方式.
我认为JSON字符串的格式不正确,无法对地图类型进行默认的GSON反序列化.
我已修改输入字符串供您考虑,这将导致非null的LocalLocationId
{
"LocalLocationId":[
[
"1",
{
"type":"folderlocation",
"id":{
"type":"locallocationid",
"id":1
},
"parentId":{
"type":"locallocationid",
"id":0
},
"name":"Test",
"accessibleToUser":true,
"defaultLocation":false,
"timezoneId":"Asia/Calcutta",
"children":[]
}
],
[
"2",
{
"type":"folderlocation",
"id":{
"type":"locallocationid",
"id":0
},
"parentId":null,
"name":"Locations",
"accessibleToUser":false,
"defaultLocation":false,
"timezoneId":"Asia/Calcutta",
"children":[{
"type":"locallocationid",
"id":1
}]
}
]
],
"allAllowedChildren":[{
"type":"locallocationid",
"id":1
}]
}
如果我对输入字符串的假设不正确,请发表评论.
编辑1:
由于无法修改输入,请考虑编写自定义解串器.
以下是注册自定义反序列化类的方法
GsonBuilder gsonb = new GsonBuilder();
gsonb.registerTypeAdapter(Tree.class, new TreeDeserializer());
Gson gson = gsonb.create();
下面是TreeDeserializer
public class TreeDeserializer implements JsonDeserializer {
public Tree deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
Tree out = new Tree();
if (json != null) {
JsonObject obj = json.getAsJsonObject();
Set> entries = obj.entrySet();
for (Map.Entry e: entries) {
if (e.getKey().equals("allAllowedChildren")) {
Type ft = List.class;
System.out.println(context.deserialize(e.getValue(), ft));
// TODO add this back into the Tree out object
} else {
// LocalLocationId
System.out.println(e.getKey());
System.out.println(context.deserialize(e.getValue(), Tree.LocalLocationId.class));
// TODO add this back into the Tree out object
}
}
}
return out;
}
}
这是Sysouts的控制台输出.
LocalLocationId [id=1]
org.test.StackOverflowAnswers.Tree$LocalLocationId@464bee09
LocalLocationId [id=0]
org.test.StackOverflowAnswers.Tree$LocalLocationId@f6c48ac
[{type=locallocationid, id=1.0}]
org.test.StackOverflowAnswers.Tree@589838eb
我将TODO留在了反序列化器中,您需要在其中编写自定义代码,以将反序列化的值注入到刚创建的Tree类中.希望这可以帮助.无法提供完整的实现,但我认为这将是部分解决方案