我有一个JSON对象的以下POJO类:
public class JSONChangeSet {
public JSONChangeSet {
System.out.println("Owner: " + owner);
}
@SerializedName("comment")
private String comment;
@SerializedName("lastUpdatedDate")
private String modifiedDate;
@SerializedName("owner")
private Resource owner;
@SerializedName("modifiedBy")
private Resource modifier;
public String getComment() {
return comment;
}
}
显然这不起作用,因为在调用构造函数时,字段所有者还没有分配值。在解析JSON对象后是否有可能自动调用方法?
答案 0 :(得分:2)
您使用gson标记了您的问题,但我建议您使用Jackson library,因为我看到了您的最后两个问题,并且看起来gson对您来说不够灵活。
在杰克逊,你的例子看起来像这样:
public final class JSONChangeSet {
private final String comment;
private final Resource owner;
@JsonCreator
public JSONChangeSet(
@JsonProperty("comment") final Resource owner,
@JsonProperty("comment") final String comment
) {
this.comment = comment;
this.owner = owner;
}
public String getComment() {
return comment;
}
}
使用此解决方案,您可以拥有由构造函数构建的不可变对象。它对DI模式也有好处。 BTW杰克逊闪电般快速。
您可能还想阅读this question。
答案 1 :(得分:1)
我认为Gson没有“倾听者”。您可以尝试以下技巧:
static class JSONChangeSet {
@SerializedName("comment")
private String comment;
@SerializedName("owner")
private int owner;
}
static class JSONChangeSetDeserializer implements JsonDeserializer<JSONChangeSet> {
Gson gson = new Gson();
@Override
public JSONChangeSet deserialize(final JsonElement json, final Type typeOfT,
final JsonDeserializationContext context) throws JsonParseException {
final JSONChangeSet obj = gson.fromJson(json, typeOfT);
// Code you want to run
System.out.println("Owner: " + obj.owner);
return obj;
}
}
public static void main(final String[] args) throws Exception, JsonMappingException, IOException {
final GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(JSONChangeSet.class, new JSONChangeSetDeserializer());
gson.create().fromJson("{\"comment\": \"it works!\", \"owner\": 23}", JSONChangeSet.class);
}