java - Play Framework: Rendering custom JSON objects -


i using play framework 1.2.4 java , using jpa persist database objects. have several model classes rendered json. problem customize these json responses , simplify objects before rendering json.

for instance, assume have object named complexclass , having properties id, name, property1,...,propertyn. in json response render id , name fields.

what elegant way of doing this? writing custom binder objects or there simple json mapping such using template?

use flexjson, it's easy. allows create jsonserializers can include/exclude fields want.

check out this article examples of using play! framework.
here's simple example:

public complexclass {    public long id;    public string name;    // , lots of other fields don't want     public string tojsonstring() {      // include id & name, exclude others.      jsonserializer ser = new jsonserializer().include(             "id",             "name",      ).exclude("*");     return ser.serialize(this);   } 

}

you can add dependencies.yml so:

require:     - play     - net.sf.flexjson -> flexjson 2.1 

what write interface models implements tojsonstring() method can call renderjson(somemodel.tojsonstring()) in controller.

link official website

edit: example lists/collections

ok, when start serializing list might unexpected results. because order of evaluation important. first include() or exclude() takes precedence on following ones.

here's example of serializing childs of parent entity (onetomany relation).

jsonserializer ser = new jsonserializer(); // exclude these standard fields childs ser.exclude(     "*.persistent",      "*.class",     "*.entityid" ); // include childs , other fields ser.include(     "childs",     "childs.*" ); // exclude else ser.exclude("*");  string data = ser.serialize(parent); 

the * wildcard way. piece of documentation explains perfectly:
an exclude of *.class match path depth. if flexjson serializing field path of "foo.bar.class" * in *.class match foo.bar.


Comments

Popular posts from this blog

delphi - How to convert bitmaps to video? -

jasper reports - Fixed header in Excel using JasperReports -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -