我正在尝试使用Gson反序列化
JSONArray,其中一个值的类型可以变化,值“in_wanted”可以是布尔值或JSONObject.
in_wanted as boolean:
{ "movies": [ { "title": "example boolean","in_wanted": false } ] }
in_wanted作为JSONObject:
{ "movies": [ { "title": "example object","in_wanted": { "profile": { "value": false } } } ] }
我需要对象,只要它可用,我需要一个反序列化器,只要“in_wanted”的值是一个布尔值,就返回null.用Gson做这件事最好的方法是什么?
解决方法
您可以使用自定义反序列化器执行此操作.在开始时,我们应该创建可以代表您的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);
原文地址:https://www.jb51.cc/java/126877.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。