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

Gson用不同的值类型反序列化json

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

Gson用不同的值类型反序列化json

您可以使用自定义解串器来完成此操作。首先,我们应该创建可以表示您的JSON的数据模型。

class JsonEntity {    private List<Movie> movies;    public List<Movie> getMovies() {        return movies;    }    public void setMovies(List<Movie> movies) {        this.movies = movies;    }    @Override    public String toString() {        return "JsonEntity [movies=" + movies + "]";    }}class Movie {    private String title;    private Profile in_wanted;    public String getTitle() {        return title;    }    public void setTitle(String title) {        this.title = title;    }    public Profile getIn_wanted() {        return in_wanted;    }    public void setIn_wanted(Profile in_wanted) {        this.in_wanted = in_wanted;    }    @Override    public String toString() {        return "Movie [title=" + title + ", in_wanted=" + in_wanted + "]";    }}class Profile {    private boolean value;    public boolean isValue() {        return value;    }    public void setValue(boolean value) {        this.value = value;    }    @Override    public String toString() {        return String.valueOf(value);    }}

现在,当我们拥有所有需要的类时,我们应该实现新的自定义反序列化器:

class ProfileJsonDeserializer implements JsonDeserializer<Profile> {    @Override    public Profile deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException {        if (jsonElement.isJsonPrimitive()) { return null;        }        return context.deserialize(jsonElement, JsonProfile.class);    }}class JsonProfile extends Profile {}

JsonProfile
上课看看。我们必须创建它以避免“反序列化循环”(棘手的部分)。

现在我们可以使用测试方法来测试我们的解决方案了:

GsonBuilder builder = new GsonBuilder();builder.registerTypeAdapter(Profile.class, new ProfileJsonDeserializer());Gson gson = builder.create();JsonEntity jsonEntity = gson.fromJson(new FileReader("/tmp/json.txt"),        JsonEntity.class);System.out.println(jsonEntity);


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

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

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