Reputation: 21
I have class WorldModel and it has ArrayList field countries, I need to serialize json with not all countries but only requested ones by client.
Is there any way to pass the argument in toJson() function? Some array or list? To serialize only fields that consider to the condition.
EDIT: added the use case code:
@ResponseBody
@RequestMapping(value = "/getWorldModel", method = RequestMethod.GET)
public String getInfrastructure(Model model, @RequestParam(value = "countries", required = true) String countries) {
Gson jsonCTS = jsonBuilder.fromWorldModelToJson();
String jCTS = jsonCTS.toJson(worldModel);
return jCTS;
}
I serialize th WorldModel worldModel object which has many countries, but I need only some of them according to client's request.
Upvotes: 0
Views: 540
Reputation: 21
I answer to my question by myself. The solution is pretty simple.
I created the special method filter which create a temporal duplicate of the object with propper fields value. So I serialize this object instead of the original one.
Upvotes: 0
Reputation: 3148
If you want to exclude some fields of object you can do it by this code:
Gson gson = new GsonBuilder()
.addSerializationExclusionStrategy(new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes f) {
//your condition
return f.getName().equal("test");
}
@Override
public boolean shouldSkipClass(Class<?> aClass) {
return false;
}
})
.create();
If you want to exclude some elements of the list you can simply edit your list by list.remove("test")
and then use the same object.
Upvotes: 1