java - How to filter properties on a self reference using Jackson? -


let's have class want serialize jackson.

public class product {     int id;     string name;     list<product> similarproducts; } 

how end this?

{     "id": 1,     "name": "product 1",     "similarproducts": [         {             "id": 2,             "name": "product 2"         },         {             "id": 3,             "name": "product 3"         }     ] } 

i've see how use @jsonproperty class or @jsonview select things seems it's class (am mistaken)? i'm not sure how work when have class that's referencing , parent has many properties, while child has few.

imagine ecommerce site , want name , url of similar products single json payload, don't need other details of similar products (children).

you can serialize using @jsonfilter annotation.

new version of model:

public class product {     int id;     string name;      @jsonfilter("productview")     list<product> similarproducts;      // getters , setters } 

serialization process:

 filterprovider filters = new simplefilterprovider()             .addfilter(                 "productview",                  simplebeanpropertyfilter.serializeallexcept("similarproducts")             );  string res = new objectmapper()             .writer(filters)             .writevalueasstring(product);  system.out.println(res); 

example

code:

product child1 = new product(); child1.id = 2; child1.name = "sfd"; product grandchild1 = new product(); grandchild1.id = 4; grandchild1.name = "werrwe"; child1.similarproducts = collections.singletonlist(grandchild1); product child2 = new product(); child2.id = 2; child2.name = "sfd";  product product = new product(); product.id = 1; product.name = "product";  product.similarproducts = arrays.aslist(child1, child2);  filterprovider filters = new simplefilterprovider().addfilter("productview",             simplebeanpropertyfilter.serializeallexcept("similarproducts"));  string res = new objectmapper().enable(serializationfeature.indent_output)             .writer(filters)             .writevalueasstring(product);  system.out.println(res); 

output:

{   "id" : 1,   "name" : "product",   "similarproducts" : [ {     "id" : 2,     "name" : "sfd"    }, {     "id" : 2,     "name" : "sfd"    } ] } 

see also

blog post filtering properties in jackson: every day jackson usage, part 3: filtering properties


Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -

Nuget pack csproj using nuspec -