GSON反序列化JSON具有不同的值类型 [英] Gson deserialize json with varying value types
问题描述
我想反序列化 JSONArray
与GSON,一个值类型可以改变,值in_wanted可以是一个布尔
或的JSONObject
。
I'm trying to deserialize a JSONArray
with Gson, one the values' type can vary, the value "in_wanted" can be either a boolean
or a JSONObject
.
in_wanted为布尔
:
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的值是一个布尔值。什么是与GSON做到这一点的最好方法是什么?
I need the object whenever it's available and i need a deserializer to return null whenever the value of "in_wanted" is a boolean. What would be the best way to do this with Gson?
推荐答案
您可以使用自定义解串器做到这一点。比赛一开始,我们应该创建数据模型,可以重新present你的JSON。
You can do this with custom deserializer. At the start we should create data model which can represent your 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);
}
}
现在,当我们拥有所有需要的类,我们应该实施新的定制解串器:
Now when we have all needed classes we should implement new custom deserializer:
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
类看看。我们必须创建它,以避免反序列化循环(棘手的问题)。
Please have a look on JsonProfile
class. We have to create it to avoid "deserialization loop" (tricky part).
现在我们可以测试我们使用的测试方法解决方案:
And now we can test our solution with test method:
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);
这篇关于GSON反序列化JSON具有不同的值类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!