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

在GSON中反序列化递归多态类

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

在GSON中反序列化递归多态类

要反序列化JSON,您需要为递归接口使用自定义反序列化器。在这种类中,您需要检查JSON并确定要实例化为JSON本身的type字段的类。在这里,您有一个我为您编写的示例基本解串器。

当然,管理边界事件可以得到改善(例如,如果没有类型字段,会发生什么情况?)。

package stackoverflow.questions;import java.lang.reflect.Type;import java.util.*;import stackoverflow.questions.Q20254329.*;import com.google.gson.*;import com.google.gson.reflect.TypeToken;public class Q20327670 {   static class Complex implements Recursive {      Map<String, Recursive> map;      @Override      public String toString() {         return "Complex [map=" + map + "]";      }   }   static class Simple implements Recursive {      @Override      public String toString() {         return "Simple []";      }   }   public static class RecursiveDeserializer implements JsonDeserializer<Recursive> {      public Recursive deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {         Recursive r = null;         if (json == null) r = null;         else { JsonElement t = json.getAsJsonObject().get("type"); String type = null; if (t != null) {    type = t.getAsString();    switch (type) {    case "complex": {       Complex c = new Complex();       JsonElement e = json.getAsJsonObject().get("map");       if (e != null) {          Type mapType = new TypeToken<Map<String, Recursive>>() {}.getType();          c.map = context.deserialize(e, mapType);       }       r = c;       break;    }    case "simple": {       r = new Simple();       break;    }    // remember to manage default..    } }         }         return r;      }   }   public static void main(String[] args) {      String json = " {        " +          "    "type" : "complex",     " +          "    "map" : {      " +          "       "a" : {     " +         "          "type" : "simple" " +         "       }, " +          "       "b" : {     " +         "          "type" : "complex",          " +          "          "map" : {" +          "   "ba" : {        " +         "       "type" : "simple"    " +         "          }          " +         "       }  " +         "    }     " +         "  }  }    ";      GsonBuilder gb = new GsonBuilder();      gb.registerTypeAdapter(Recursive.class, new RecursiveDeserializer());      Gson gson = gb.create();      Recursive r = gson.fromJson(json, Recursive.class);      System.out.println(r);   }}

这是我的代码的结果:

Complex [map={a=Simple [], b=Complex [map={ba=Simple []}]}]


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

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

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