如何将JSON字符串反序列化为对象

如何将JSON字符串反序列化为对象,第1张

如何将JSON字符串反序列化为对象

@基达

假设您可以控制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<Tree> {    public Tree deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {        Tree out = new Tree();        if (json != null) { JsonObject obj  = json.getAsJsonObject(); Set<Map.Entry<String,JsonElement>> entries = obj.entrySet(); for (Map.Entry<String, JsonElement> 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@464bee09LocalLocationId [id=0]org.test.StackOverflowAnswers.Tree$LocalLocationId@f6c48ac[{type=locallocationid, id=1.0}]org.test.StackOverflowAnswers.Tree@589838eb

我将TODO留在了反序列化器中,您需要在其中编写自定义代码,以将反序列化的值注入到刚刚创建的Tree类中。希望这可以帮助。无法提供完整的实现,但我认为这将是部分解决方案



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5507519.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-13
下一篇 2022-12-13

发表评论

登录后才能评论

评论列表(0条)

保存