Android : Jackson with ActiveAndroid
ActiveAndroid has a constraint that all its entities need to inherit from a certain base class and need to have a one parameter constructor taking in the Context (from the activity) as the input. [Not a fan to this constraint].
With gson, I can create a type adapter to get around this constraint.
public class PolicyInstanceCreator implements InstanceCreator<Policy>{
private Context context;
public PolicyInstanceCreator(Context context) {
this.context = context;
}
@Override
public Policy createInstance(Type type) {
return new Policy(context);
}
}
Gson gson = new GsonBuilder().registerTypeAdapter(Policy.class, new PolicyInstanceCreator(context)).create();
Policy[] policies = gson.fromJson(myString, Policy[].class);
开发者_C百科
One possibility seems to be that we need to implement a custom desearlizer with Jackson.
Are there any alternatives to having to write a custom deserializer for jackson or is that my only option with a specific one parameter constructor?
Please let me know if there are any alternative.
Thanks
One alternative is to apply mix-in annotations (see this wiki, or this blog post) to add @JsonCreator to specify that this specific constructor is to be used. This requires either that 'Context' comes from JSON (name in JSON can be specified with @JsonProperty on constructor parameter); or that it is ok to pass in null (which occurs if no such field is found from JSON). If an actual external context object needs to be passed, custom deserializer is the way to go (until 'external value injection' is implemented; this is planned but not yet added).
精彩评论