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

使用GSON解析JSON时使用枚举

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

使用GSON解析JSON时使用枚举

从Gson的文档中:

Gson为枚举提供了默认的序列化和反序列化…如果您想更改默认的表示形式,则可以通过GsonBuilder.registerTypeAdapter(Type,Object)注册类型适配器来实现。

以下是一种这样的方法。

import java.io.FileReader;import java.lang.reflect.Type;import java.util.List;import com.google.gson.Gson;import com.google.gson.GsonBuilder;import com.google.gson.JsonDeserializationContext;import com.google.gson.JsonDeserializer;import com.google.gson.JsonElement;import com.google.gson.JsonParseException;public class GsonFoo{  public static void main(String[] args) throws Exception  {    GsonBuilder gsonBuilder = new GsonBuilder();    gsonBuilder.registerTypeAdapter(AttributeScope.class, new AttributeScopeDeserializer());    Gson gson = gsonBuilder.create();    TruncateElement element = gson.fromJson(new FileReader("input.json"), TruncateElement.class);    System.out.println(element.lower);    System.out.println(element.upper);    System.out.println(element.delimiter);    System.out.println(element.scope.get(0));  }}class AttributeScopeDeserializer implements JsonDeserializer<AttributeScope>{  @Override  public AttributeScope deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)      throws JsonParseException  {    AttributeScope[] scopes = AttributeScope.values();    for (AttributeScope scope : scopes)    {      if (scope.scope.equals(json.getAsString()))        return scope;    }    return null;  }}class TruncateElement{  int lower;  int upper;  String delimiter;  List<AttributeScope> scope;}enum AttributeScope{  TITLE("${title}"), DEscriptION("${description}");  String scope;  AttributeScope(String scope)  {    this.scope = scope;  }}


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

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

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