栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何将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类中。希望这可以帮助。无法提供完整的实现,但我认为这将是部分解决方案



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/516368.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号